使用反射调用泛型扩展方法

本文关键字:扩展 方法 泛型 调用 反射 | 更新日期: 2023-09-27 18:10:24

我试图调用一个动态类型的泛型扩展方法,但我一直得到一个错误。

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

使用反射调用泛型扩展方法

Name没有公共的无参数构造函数。
但是,您将T约束为IDifference, new(),这意味着用作泛型参数的每个类型都必须实现IDifference,并且必须有一个公共的无参数构造函数。

BTW: IDifferenceExtensions是一个非常糟糕的静态类名。I前缀通常为接口保留。