在 C#.NET 中动态转换为类型

发布于 2024-12-07 11:52:11 字数 715 浏览 0 评论 0原文

替代标题:在运行时动态转换为类型。

我想将对象转换为将在运行时分配的类型。

例如,假设我有一个函数将字符串值(来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

嘴硬脾气大 2024-12-14 11:52:11

您需要使用 Convert.ChangeType(...) 函数 [注意:在下面的函数中,输入 propertyValue 可以很容易地成为对象类型...我刚刚预制了一个字符串版本]:

/// <summary>
/// Sets a value in an object, used to hide all the logic that goes into
///     handling this sort of thing, so that is works elegantly in a single line.
/// </summary>
/// <param name="target"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValueFromString(this object target,               
                              string propertyName, string propertyValue)
{
    PropertyInfo oProp = target.GetType().GetProperty(propertyName);
    Type tProp = oProp.PropertyType;

    //Nullable properties have to be treated differently, since we 
    //  use their underlying property to set the value in the object
    if (tProp.IsGenericType
        && tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        //if it's null, just set the value from the reserved word null, and return
        if (propertyValue == null)
        {
            oProp.SetValue(target, null, null);
            return;
        }

        //Get the underlying type property instead of the nullable generic
        tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
    }

    //use the converter to get the correct value
    oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null);
}

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]:

/// <summary>
/// Sets a value in an object, used to hide all the logic that goes into
///     handling this sort of thing, so that is works elegantly in a single line.
/// </summary>
/// <param name="target"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValueFromString(this object target,               
                              string propertyName, string propertyValue)
{
    PropertyInfo oProp = target.GetType().GetProperty(propertyName);
    Type tProp = oProp.PropertyType;

    //Nullable properties have to be treated differently, since we 
    //  use their underlying property to set the value in the object
    if (tProp.IsGenericType
        && tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        //if it's null, just set the value from the reserved word null, and return
        if (propertyValue == null)
        {
            oProp.SetValue(target, null, null);
            return;
        }

        //Get the underlying type property instead of the nullable generic
        tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
    }

    //use the converter to get the correct value
    oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null);
}
如日中天 2024-12-14 11:52:11

您正在寻找通用类型转换器!?这不是一件容易的事..

尝试这种方法:

通用类型转换器

您可以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.

一萌ing 2024-12-14 11:52:11

我不确定它是否有效,但请尝试一下:

public static T To<T>(this IConvertible obj)
{
  return (T)Convert.ChangeType(obj, typeof(T));
}

Public void Foo(object obj,string propertyName,object value)
{
    Type t= obj.GetType().GetProperty(propName).PropertyType;
    obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null);
}

I'm not sure it works, but give it a try:

public static T To<T>(this IConvertible obj)
{
  return (T)Convert.ChangeType(obj, typeof(T));
}

Public void Foo(object obj,string propertyName,object value)
{
    Type t= obj.GetType().GetProperty(propName).PropertyType;
    obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null);
}
空城仅有旧梦在 2024-12-14 11:52:11

这是另一种方法,但我不确定

不支持泛型类型:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 

支持泛型类型:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    if (type.IsGenericType)
        type = type.GetGenericArguments()[0];

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 

Here's another way you can do it, but I'm not sure

Without support for generic types:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 

With support for generic types:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    if (type.IsGenericType)
        type = type.GetGenericArguments()[0];

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 
谜兔 2024-12-14 11:52:11

我使用了 C# 中的 Convert 函数。我进行转换的方式是使用反射。:

Type type = this.myObject.GetType();

if (type.Name == "MyObjectClass") {
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));

这一切都假设您知道要转换成什么类型​​。您甚至可以进行切换并拥有想要反映的多种类型。

I used the Convert function in C#. The way I'm doing my conversion is using reflection.:

Type type = this.myObject.GetType();

if (type.Name == "MyObjectClass") {
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文