这是我的代码。它抛出异常“类型'MyEnum.CommonCoreStandard'的对象不能转换为类型'System.Nullable`1 [System.Byte]'。”同时设置第二个属性“Prop2”的值。我使用反射的概念,以一种“BlEntity”转换成另一种类型的“UiEntity”如何使用PropertyInfo.SetValue方法设置可为空属性的值(对象,对象)
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);
}
}
参见[这个答案](http://stackoverflow.com/questions/3531318/convert-changetype - 可空数类型) – 2013-02-14 15:04:45
此外,“它正在失败”是*从来没有足够的细节。请阅读http://tinyurl.com/so-list以获取发布问题时要检查的事项列表。 – 2013-02-14 15:27:50
我简单地使用了“它正在失败”的声明,因为可以查看完整的代码。现在我进行了更正并指定了抛出的完整异常消息。 – Vijay 2013-02-14 16:19:39