【问题标题】:Casting To A Property's Type Using Convert.ChangeType使用 Convert.ChangeType 转换为属性的类型
【发布时间】:2013-12-21 16:29:16
【问题描述】:

我需要遍历对象的属性并获取每个原始属性(和字符串)的值。我已经有了处理索引器、复杂对象和可为空的原语的代码,所以不用担心这些(我从代码中排除了这些以保持简单)。我遇到的问题是当我使用 Convert.ChangeType() 时。变量“值”始终是 System.Object 类型。如何将其转换为“SomeObject”对象中所示的字符串或 int?

SomeObject someObject = new SomeObject();

foreach (PropertyInfo propertyInfo in someObject.GetType().GetProperties())
{
    Type propertyType = propertyInfo.PropertyType;

    // How can I cast this to the type of "propertyType"?
    var value = Convert.ChangeType(propertyInfo.GetValue(someObject, null), propertyType);
}

public class SomeObject
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
}

【问题讨论】:

    标签: c# .net object properties casting


    【解决方案1】:

    你可以这样做

    if (propertyType == typeof(int))
    {
        var value = (int)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
    }
    else if(propertyType == typeof(string))
    {
        var value = (string)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 2022-11-16
      相关资源
      最近更新 更多