2013-04-22 42 views
1

我正在嘗試使用動態類型調用通用擴展方法,但不斷收到錯誤。調用帶反射的通用擴展方法

GenericArguments[0], 'DifferenceConsole.Name', on 'DifferenceConsole.Difference'1[T] GetDifferences[T](T, T)' violates the constraint of type 'T'.

在下面的代碼,我曾嘗試註釋掉動態類型,只是一個硬編碼類型,應該工作(名稱),但我得到同樣的錯誤。我不明白我爲什麼會遇到錯誤。有什麼建議?

public static class IDifferenceExtensions 
{ 
    public static Difference<T> GetDifferences<T>(this T sourceItem, T targetItem) where T : IDifference, new() 
    { 
     Type itemType = sourceItem.GetType(); 

     foreach (PropertyInfo prop in itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) 
     { 
      DifferenceAttribute diffAttribute = prop.GetCustomAttributes(typeof(DifferenceAttribute), false).FirstOrDefault() as DifferenceAttribute; 

      if (diffAttribute != null) 
      { 
       if (prop.PropertyType.GetInterfaces().Contains(typeof(IDifference))) 
       { 
        object sourceValue = prop.GetValue(sourceItem, null); 
        object targetValue = prop.GetValue(targetItem, null); 

        MethodInfo mi = typeof(IDifferenceExtensions) 
         .GetMethod("GetDifferences") 
         .MakeGenericMethod(typeof(Name)); // <-- Error occurs here 
         //.MakeGenericMethod(prop.PropertyType); 

        // Invoke and other stuff 


       } 
       else 
       { 
        // Other stuff 
       } 
      } 
     } 

     //return diff; 
    } 
} 

public class Name : IDifference 
{ 
    [Difference] 
    public String FirstName { get; set; } 

    [Difference] 
    public String LastName { get; set; } 

    public Name(string firstName, string lastName) 
    { 
     this.FirstName = firstName; 
     this.LastName = lastName; 
    } 
} 

public interface IDifference 
{ 

} 

public class Difference<T> where T: IDifference, new() 
{ 
    public T Item { get; set; } 

    public Difference() 
    { 
     Item = new T(); 
    } 
} 

回答

1

Name沒有一個公開,無參數構造函數。
但是,您將T限制爲IDifference, new(),這意味着用作泛型參數的每個類型必須實現IDifference並且必須具有公共的無參數構造函數。

作者:IDifferenceExtensions對於靜態類來說是一個非常糟糕的名字。前綴I通常保留給接口。

+0

Doh!在我的腦海裏,它確實有一個無參數的構造函數。我很確定,我從來沒有打擾過去看看。感謝您的命名建議! – 2013-04-22 13:57:47