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


- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01