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 的动态解析
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
