在运行时分配类型 [英] Assigning type at runtime
问题描述
我有一个 T 类型的变量 x 和一个字符串中的值.例如我有:
I have a variable x of type T and value that is in a string. For example I have:
bool x, value = "True"
int x, value = "1"
- 是否有一种通用的方法来分配/解析/反序列化 x 的值?
注意 T 可能是引用类型或原始类型!
Note that T may be referenced or primitive type!
推荐答案
您可以使用 Convert.ChangeType
方法.
you can use Convert.ChangeType
method.
这将涵盖所有基本类型的转换.
This will cover all base types conversion.
示例:var i = Convert.ChangeType("1", typeof(int));
您还可以查看IConvertible
界面 可用于将自己的对象从其他类型转换为另一种类型.
You can also take a look at the IConvertible
interface that you can use for converting your own objects from or to another type.
最后,正如 codymanix 所说,您可以依靠 OOB XmlSerialization 或 Binary Serialization 来序列化您的对象.
Finally, as codymanix said, you can rely on the OOB XmlSerialization or Binary Serialization to serialize your objects.
您可以在编译时检查目标类型是否可转换,方法是将 convert.ChangeType 方法包装在这样的实用程序类中:
public static class ConvertUtility
{
public static T Convert<T>(object source) where T : IConvertible
{
return (T)System.Convert.ChangeType(source, typeof(T));
}
}
这篇关于在运行时分配类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!