[英]Type casting using string of type
I have fully qualified class name which I have to use for type casting. 我有完全限定的类名,必须用于类型转换。 I can get type using
我可以使用输入
someType=Type.GetType("TypeName").
After Deserializing I am getting object which I have to typecast into particular type ie TypeName. 反序列化之后,我得到的对象必须类型转换为特殊类型,即TypeName。
I tried 我试过了
obj = (someType) SXmlSerializer.Deserialize("TypeName", someData);
but that doesn't works . 但这没用。 Is there any option available to do typecasting using only class name as string?
是否可以使用仅将类名作为字符串进行类型转换的选项?
I have to convert it into someType because I have to modify value for property ie obj.SomeProperty = "AnotherValue"
. 我必须将其转换为someType,因为我必须修改属性的值,即
obj.SomeProperty = "AnotherValue"
。
I have to convert it into someType because I have to modify value for property ie obj.SomeProperty = "AnotherValue".
我必须将其转换为someType,因为我必须修改属性的值,即obj.SomeProperty =“ AnotherValue”。
But if you don't know the type at compile time, how do you know it has a SomeProperty
property? 但是,如果您在编译时不知道该类型,那么您如何知道它具有
SomeProperty
属性?
If you want to assume that it does and defer type-checking to runtime then you could use dynamic
: 如果你要认为它并推迟类型检查运行时,那么你可以使用
dynamic
:
dynamic obj = SXmlSerializer.Deserialize("TypeName", someData);
then you can do 那你就可以
obj.SomeProperty = "AnotherValue";
Which will fail at runtime if the object does not have a SomeProperty
property. 如果对象没有
SomeProperty
属性,它将在运行时失败。
Casting only affects how methods are bound at compile-time. 强制转换仅影响在编译时如何绑定方法。 There's no value in casting if you don't know the type at compile-time.
如果您在编译时不知道类型,则转换没有任何价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.