在 C#.NET 中动态转换为类型
替代标题:在运行时动态转换为类型。
我想将对象转换为将在运行时分配的类型。
例如,假设我有一个函数将字符串值(来自 TextBox 或 Dropdownlist
)分配给 Object.Property
。
我如何将值转换为正确的类型?例如,它可以是整数、字符串或枚举。
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
Alternative Title: Dynamically convert to a type at runtime.
I want to to convert an Object to a type that will be assigned at runtime.
For example, assume that I have a function that assigns a string value(from a TextBox or Dropdownlist
) to an Object.Property
.
How would I convert the value to proper type? For instance, it could be an integer, string, or enum.
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用 Convert.ChangeType(...) 函数 [注意:在下面的函数中,输入 propertyValue 可以很容易地成为对象类型...我刚刚预制了一个字符串版本]:
You need to use the Convert.ChangeType(...) function [note: in the function below, the input propertyValue could just as easily have been of type object ... I just had a string version pre-baked]:
您正在寻找通用类型转换器!?这不是一件容易的事..
尝试这种方法:
通用类型转换器
您可以NuGet
Install-Package UniversalTypeConverter
另外,这里不可能使用
Generics
吗?如果您至少知道转换的目标类型,这将有助于解决问题。A universal Type Converter is what you seek !? Not an easy feat..
Try this approach:
Universal Type Converter
You can in NuGet
Install-Package UniversalTypeConverter
Also, is using
Generics
out of the question here? It would facilitate the solution if you know at least the target type of the conversion.我不确定它是否有效,但请尝试一下:
I'm not sure it works, but give it a try:
这是另一种方法,但我不确定
不支持泛型类型:
支持泛型类型:
Here's another way you can do it, but I'm not sure
Without support for generic types:
With support for generic types:
我使用了 C# 中的 Convert 函数。我进行转换的方式是使用反射。:
这一切都假设您知道要转换成什么类型。您甚至可以进行切换并拥有想要反映的多种类型。
I used the Convert function in C#. The way I'm doing my conversion is using reflection.:
This is all assuming you know what type you want to convert into. You can even make a switch and have multiple types you want to reflect too.