C#:来自 System.Type 的动态解析 [英] C#: Dynamic parse from System.Type

查看:18
本文介绍了C#:来自 System.Type 的动态解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Type, a String and an Object.

有什么方法可以调用解析方法或动态转换字符串上的那种类型吗?

Is there some way I can call the parse method or convert for that type on the string dynamically?

基本上如何删除此逻辑中的 if 语句

Basically how do I remove the if statements in this logic

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);
}

做一些类似这样的事情.

And do someting more like this.

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 和许多其他内置类型)已经集成到 TypeConverter 基础结构中,因此支持开箱即用".

All primitive types (plus Nullable<TPrimitive>, and numerous other built-in types) are integrated into the TypeConverter infrastructure already, and are thus supported 'out-of-the-box'.

要将自定义类型集成到 TypeConverter 基础架构中,请实现您自己的 TypeConverter 并使用 TypeConverterAttribute 来装饰要转换的类,用你的新 TypeConverter

To integrate a custom type into the TypeConverter infrastructure, implement your own TypeConverter and use TypeConverterAttribute to decorate the class to be converted, with your new TypeConverter

这篇关于C#:来自 System.Type 的动态解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆