【问题标题】:How to set the value of nullable property using PropertyInfo.SetValue Method (Object, Object) [duplicate]如何使用 PropertyInfo.SetValue 方法(对象,对象)设置可为空属性的值
【发布时间】:2013-02-14 15:02:09
【问题描述】:

这是我的代码。它抛出异常“'MyEnum.CommonCoreStandard'类型的对象无法转换为'System.Nullable`1 [System.Byte]'类型。”同时设置第二个属性“Prop2”的值。我正在使用反射的概念将一种类型“BlEntity”转换为另一种类型“UiEntity”

public class BlEntity
{
    //CommonCoreStandard is an enum
    public CommonCoreStandard Prop1 { get; set; }
    public CommonCoreStandard? Prop2 { get; set; }
}

public class UiEntity
{
    public byte Prop1 { get; set; }
    public byte? Prop2 { get; set; }
}

 public void ConvertBlToUi()
    {
        var source = new BlEntity(CommonCoreStandard.KeyIdeasAndDetails, CommonCoreStandard.IntegrationOfKnowledge);
        var target = new UiEntity();

        TypeConverter.ConvertBlToUi(source,target);
 }

    public static void ConvertBlToUi<TBl, TUi>(TBl entitySource, TUi entityTarget)
    {
        var blProperties = typeof(TBl).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p }).ToArray();

        var uiProperties = typeof(TUi).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p });

        foreach (var uiProperty in uiProperties)
        {
            var value = blProperty.Property.GetValue(entitySource);
            uiProperty.Property.SetValue(entityTarget, value);
        }

    }

【问题讨论】:

  • 另外,“它正在失败”是永远不够详细的。请阅读tinyurl.com/so-list,了解您发布问题时要检查的事项列表。
  • 我只是使用了“它正在失败”的语句,因为可以查看完整的代码。现在我进行了更正并指定了抛出的完整异常消息。
  • 我还想补充一点,如果我将第一个属性“Prop1”声明为“DateTime?”那么上面的代码也适用于设置“Prop1”的值,但不适用于“prop2”。所以我相信有一些特定于“字节”的东西?或可为空的字节。

标签: c# generics


【解决方案1】:
    public static void ConvertBlToUi<TBl, TUi>(TBl entitySource, TUi entityTarget)
    {
        var blProperties = typeof(TBl).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p }).ToArray();

        var uiProperties = typeof(TUi).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p });

        foreach (var uiProperty in uiProperties)
        {
            var value = blProperty.Property.GetValue(entitySource);
            var t = Nullable.GetUnderlyingType(uiProperty.Property.PropertyType) ?? uiProperty.Property.PropertyType;
            var safeValue = (value == null) ? null : Convert.ChangeType(value, t);
            uiProperty.Property.SetValue(entityTarget, safeValue);
        }
    }

【讨论】:

猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2019-05-15
  • 2011-07-16
  • 2023-03-26
  • 2013-06-30
  • 2019-03-24
相关资源
最近更新 更多