2010-08-26 21 views
5

好的,所以我正在學習泛型,我試圖讓這個東西運行,但它一直說我有同樣的錯誤。下面的代碼:非靜態方法需要PropertyInfo.SetValue中的目標

public static T Test<T>(MyClass myClass) where T : MyClass2 
{ 
    var result = default(T); 
    var resultType = typeof(T); 
    var fromClass = myClass.GetType(); 
    var toProperties = resultType.GetProperties(); 

    foreach (var propertyInfo in toProperties) 
    { 
     var fromProperty = fromClass.GetProperty(propertyInfo.Name); 
     if (fromProperty != null) 
      propertyInfo.SetValue(result, fromProperty, null); 
    } 

    return result; 
} 

回答

8

發生這種情況是因爲default(T)返回null,因爲T表示引用類型。參考類型的默認值是null

你可以在你的方法更改爲:

public static T Test<T>(MyClass myClass) where T : MyClass2, new() 
{ 
    var result = new T(); 
    ... 
} 

,然後它會按照您希望它。當然,MyClass2及其後代現在必須具有無參數的構造函數。

+0

謝謝,這正是我一直在尋找... – 2010-08-26 17:16:27

3

的這裏的問題是,從T派生MyClass,因此是引用類型。所以表達式default(T)將返回值null。以下對SetValue的調用操作了一個null值,但該屬性是一個實例屬性,因此您將獲得指定的消息。

你需要做以下

  1. 一個合格的T一個真正的實例的測試功能設置上
  2. 的屬性值只有在類型設置的靜態屬性
1

而不是

propertyInfo.SetValue(result, fromProperty, null); 

嘗試:

foreach (var propertyInfo in toProperties) 
{ 
    propertyInfo.GetSetMethod().Invoke(MyClass2, new object[] 
    { 
     MyClass.GetType().GetProperty(propertyInfo.Name). 
     GetGetMethod().Invoke(MyClass, null) 
    }); 
} 
相關問題