Pav*_*vel 2 generics casting deserialization c#-4.0 binary-deserialization
我有一个可以序列化的通用类:
MyOwnGenericClass<T>
Run Code Online (Sandbox Code Playgroud)
所以我想反序列化它,如果T
是一个String
实例处理它,在另一种情况下我想抛出异常。
反序列化时如何知道泛型包含的类型MyOwnGenericClass<T>
?我必须将以下代码投射到哪个类?
new BinaryFormatter().Deserialize(fileStrieam);
Run Code Online (Sandbox Code Playgroud)
这真的很容易。object
就像这样使用:
object obj = new BinaryFormatter().Deserialize(fileStrieam);
Run Code Online (Sandbox Code Playgroud)
然后按照你说的去做:
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();
}
Run Code Online (Sandbox Code Playgroud)
所以你没有检查是否T
是一个string
. 您要检查的不仅仅是这些:您要检查 obj 是否是MyOwnGenericClass< string >
. 没有人说它永远是一个MyOwnGenericClass< something >
,而我们唯一头痛的是找到它是什么。
您可以发送布尔值、字符串、整数、整数的原始数组,甚至是StringBuilder
. 然后是你的随行人员:你可以发送MyOwnGenericClass< int >
,MyOwnGenericClass< string >
(这是你唯一接受的)。
归档时间: |
|
查看次数: |
2071 次 |
最近记录: |