多次调用MakeGenericType(...)每次都会创建一个新类型吗?

Tom*_*Tom 7 c# generics system.reflection ef-code-first

我有一个Entity Framework Code First模型,我为此创建了一个静态泛型类,它有一个搜索方法,可以为列表中的每个项调用.承认这是我的头脑,我认为使类静态可以提高代码清晰度甚至性能,因为不必在许多不同的地方创建实例.所有这一切的目标是自动化用户可以搜索,导出哪些属性.

主要问题是:如果为具有引用类型属性的每个项(可能是1000个)调用MakeGenericType(...),那么该引用类型属性的泛型类型是一次生成并保存在某处或生成1000次?

指出任何其他性能犯罪或代码味道是值得赞赏的.

public static class SearchUserVisibleProperties<T>
{
    private static List<PropertyInfo> userVisibleProperties { get; set; }

    static SearchUserVisibleProperties()
    {
        userVisibleProperties = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(UserVisibleAttribute))).ToList();
    }

    public static bool search(T item, string searchString)
    {
        foreach (PropertyInfo pInfo in userVisibleProperties)
        {
            object value = pInfo.GetValue(item);
            if (value == null)
            {
                continue;
            }
            if (pInfo.PropertyType == typeof(string) || pInfo.PropertyType.IsValueType)
            {
                ...unrelevant string matching code...
            }
            else if ((bool)typeof(SearchUserVisibleProperties<>).MakeGenericType(new Type[] { value.GetType() }).InvokeMember(nameof(search), BindingFlags.InvokeMethod, null, null, new object[] { value, searchString }))
            {
                return true;
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

文档MakeGenericType建议为泛型类型定义和泛型类型参数的相同组合返回的类型将是相同的:

Type返回的对象MakeGenericTypeType通过调用GetType结果构造类型的方法获得的对象相同,或者GetType使用相同类型参数从相同泛型类型定义创建的任何构造类型的方法.

这是一个小实验,表明以上是正确的:

var a = typeof(Tuple<,>).MakeGenericType(typeof(int), typeof(char));
var b = typeof(Tuple<,>).MakeGenericType(typeof(int), typeof(char));
var c = typeof(Tuple<int,char>);
Console.WriteLine(ReferenceEquals(a, b)); // True
Console.WriteLine(ReferenceEquals(a, c)); // True
Run Code Online (Sandbox Code Playgroud)