c# - 多次调用 MakeGenericType(...) 是否每次都创建一个新类型?

标签 c# generics ef-code-first system.reflection

我有一个 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;
    }
}

最佳答案

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

The Type object returned by MakeGenericType is the same as the Type obtained by calling the GetType method of the resulting constructed type, or the GetType method of any constructed type that was created from the same generic type definition using the same type arguments.

下面是一个小实验来证明以上是正确的:

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

关于c# - 多次调用 MakeGenericType(...) 是否每次都创建一个新类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45938823/

相关文章:

c# - 如何在 Winforms 中包含控制台?

c# - 将 C# Type 转换为 type 数组的类型

java - 没有参数的泛型方法

java - 尝试避免返回 NULL 时键入安全警告

c# - 不使用 NHibernate 对象返回列表

c# - 当我的播放器死机时,如何关闭特定音频?

c# - 应用程序级全局异常处理程序没有被命中

typescript - 如何使用 typescript 创建 EventHandler 类?

asp.net-mvc-3 - Mvc脚手架 : How to support many-to-many relationships between entities

entity-framework - EF 4.2,代码优先 - 复杂类型中的导航属性