2013-02-14 235 views
0

這是我的代碼。它拋出異常「類型'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); 
     } 

    } 
+0

參見[這個答案](http://stackoverflow.com/questions/3531318/convert-changetype - 可空數類型) – 2013-02-14 15:04:45

+0

此外,「它正在失敗」是*從來沒有足夠的細節。請閱讀http://tinyurl.com/so-list以獲取發佈問題時要檢查的事項列表。 – 2013-02-14 15:27:50

+0

我簡單地使用了「它正在失敗」的聲明,因爲可以查看完整的代碼。現在我進行了更正並指定了拋出的完整異常消息。 – Vijay 2013-02-14 16:19:39

回答

4
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); 
     } 
    } 
+0

我得到這個答案的提示是從鏈接「http://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types」 – Vijay 2013-02-14 16:33:13

相關問題