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 的动态解析
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
