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

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

问题描述

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

有一些方法我可以调用parse方法或转换为该类型的字符串动态?

基本上,我怎么删除if语句在这样的逻辑

 对象值=新的对象();
字符串MyString的=东西;
键入propType = p.PropertyType;

如果(propType == Type.GetType(日期时间))
{
    值= DateTime.Parse(myString的);
}

如果(propType == Type.GetType(INT))
{
    值= int.Parse(MyString的);
}
 

和不治本更多这样的。

 对象值=新的对象();
字符串MyString的=东西;
键入propType = p.PropertyType;


//这实际上并没有正常工作
值= propType .Parse(MyString的);
 

解决方案

<一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx"><$c$c>TypeDescriptor救援:

  VAR转换器= TypeDescriptor.GetConverter(propType);
VAR的结果= converter.ConvertFrom(MyString的);
 

要融入类型转换器基础设施,实现自己的<一href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx"><$c$c>TypeConverter和装饰类转换它与<一href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverterattribute.aspx"><$c$c>TypeConverterAttribute

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?

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 to rescue:

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

To integrate into TypeConverter infrastructure, implement your own TypeConverter and decorate class to be converted with it with TypeConverterAttribute

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

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