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

C#: Dynamic parse from System.Type(C#:来自 System.Type 的动态解析)
本文介绍了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 的动态解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)