gpt4 book ai didi

c# - 如何使用 PropertyInfo.SetValue Method (Object, Object) 设置可空属性的值

转载 作者:行者123 更新时间:2023-12-03 23:32:19 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Convert.ChangeType() fails on Nullable Types

(7 个回答)


8 年前关闭。




这是我的代码。它抛出异常“类型'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);
}

}

最佳答案

    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);
}
}

关于c# - 如何使用 PropertyInfo.SetValue Method (Object, Object) 设置可空属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com