我有一个可序列化泛型类:二进制反序列化的通用对象
MyOwnGenericClass<T>
所以我想反序列化,如果T
是String
情况下处理它,在另一种情况下,我想抛出一个例外。
如何知道类型的泛型包含在MyOwnGenericClass<T>
而反序列化? 到什么班我必须投下下面的代码?
new BinaryFormatter().Deserialize(fileStrieam);
我有一个可序列化泛型类:二进制反序列化的通用对象
MyOwnGenericClass<T>
所以我想反序列化,如果T
是String
情况下处理它,在另一种情况下,我想抛出一个例外。
如何知道类型的泛型包含在MyOwnGenericClass<T>
而反序列化? 到什么班我必须投下下面的代码?
new BinaryFormatter().Deserialize(fileStrieam);
那真的很容易。只需使用object
像这样:
object obj = new BinaryFormatter().Deserialize(fileStrieam);
,然后做什么,你说你会做:
if (!(obj is MyOwnGenericClass<string>))
throw new Exception("It was something other than MyOwnGenericClass<string>");
else {
MyOwnGenericClass<string> asMyOwn_OfString = obj as MyOwnGenericClass<string>;
// do specific stuff with it
asMyOwn.SpecificStuff();
}
所以你不检查,如果T
是string
。 你检查的不仅仅是:你正在检查obj是否是MyOwnGenericClass<string>
。 没有人会说它永远是MyOwnGenericClass<something>
,唯一让我们头疼的是要找出那是什么东西。
您可以发送bools,字符串,整数,int基本数组,甚至可以发送StringBuilder
。 然后你的随从:你可以发送MyOwnGenericClass<int>
,MyOwnGenericClass<string>
(这是你唯一接受的)。
+1:使用'is'是一个比我更不傻的方法 – millimoose 2013-02-28 02:11:05
var test = new MyGenericType<string>();
var genericTypes = test.GetType().GetGenericArguments();
if (genericTypes.Length == 1 && genericTypes[0] == typeof(string))
{
// Do deserialization
}
else
{
throw new Exception();
}
您可以使用Type.GetGenericArguments()
获得的类型与在运行时创建通用的实际参数值:
class MyGeneric<TValue> {}
object stringValue = new MyGeneric<string>();
object intValue = new MyGeneric<int>();
// prints True
Console.WriteLine(stringValue.GetType().GetGenericArguments()[0] == typeof(string));
// prints False
Console.WriteLine(intValue.GetType().GetGenericArguments()[0] == typeof(string));
http://msdn.microsoft.com/en-us/library/system.type.aspx - 搜索“泛型”,其中一种方法/属性很可能就是您要查找的内容。 – millimoose 2013-02-27 17:09:33
“所以我想反序列化它,如果T是一个String实例处理它,在另一种情况下,我想抛出一个异常。”难道你们的班级是通用的吗? – bas 2013-02-27 17:17:31
@bas哦,是啊:)我重读了我的问题,并意识到这有点冲突......这不是我真正需要的,但是如果我知道如何做到这一点,我就可以做我真正需要的东西。 – 2013-02-27 17:40:38