C#:来自 System.Type 的动态解析

标签 c# .net type-conversion

我有一个类型、一个字符串和一个对象。

有什么方法可以动态地调用解析方法或对字符串进行该类型的转换?

基本上我如何删除这个逻辑中的 if 语句

object value = new object();    
String myString = "something";
Type propType = p.PropertyType;

if(propType == Type.GetType("DateTime"))
{
    value = DateTime.Parse(myString);
}

if (propType == Type.GetType("int"))
{
    value = int.Parse(myString);
}

再做一些类似的事情。

object value = new object();
String myString = "something";
Type propType = p.PropertyType;


//this doesn't actually work
value = propType .Parse(myString);  

最佳答案

TypeDescriptor 救援!:

var converter = TypeDescriptor.GetConverter(propType);
var result = converter.ConvertFrom(myString);

所有基本类型(加上 Nullable<TPrimitive> 和许多其他内置类型)都已经集成到 TypeConverter 基础架构中,因此“开箱即用”。

将自定义类型集成到 TypeConverter基础设施,实现你自己的 TypeConverter 并使用 TypeConverterAttribute 用新的 TypeConverter 装饰要转换的类

关于C#:来自 System.Type 的动态解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2380467/

相关文章:

c# - Application_Start 事件中的请求对象

c# - 如何从 C# 连接英特尔的新 DRNG(RDRAND 指令)?

c# - 为什么 'stackalloc' 关键字不适用于属性?

ruby - 使用默认值将 Ruby 字符串转换为整数

java - JSONObject无法通过方法调用转换转换为String

c# - Entity Framework 4 - 删除对象

c# - 为什么一个null返回可以被测试而另一个会抛出异常?

c# - ServiceStack API 和 ASP MVC Authentication 两种方式

.net - ASP.Net https 与 http

C: 指针类型之间的非法转换:指向 const unsigned char 的指针 -> 指向 unsigned char 的指针