我有一个可以序列化的泛型类:
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 >
,我们唯一的头痛是找到这个东西是什么。
你可以发送bool, string, int, int的基本数组,甚至是StringBuilder
。然后是你的随从:你可以发送MyOwnGenericClass< int >
, MyOwnGenericClass< string >
(这是你唯一接受的)。
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));