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();
}
}
Doh! 내 머리 속에는 매개 변수없는 생성자가있었습니다. 나는 그것에 대해 확신했기 때문에 결코 보지 못했습니다. 명명 조언에 너무 감사드립니다! –