1

動的な型でジェネリック拡張メソッドを呼び出そうとしていますが、エラーが発生し続けます。

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

以下のコードでは、動的タイプをコメントアウトして、動作するはずのタイプ (Name) をハードコーディングしようとしましたが、同じエラーが発生します。エラーが発生する理由がわかりません。何かアドバイス?

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

1 に答える 1