相关疑难解决方法(0)

为什么c#编译器在使用new()约束的泛型类型调用new in时会发出Activator.CreateInstance?

如果您有以下代码:

static T GenericConstruct<T>() where T : new()
{
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

C#编译器坚持发出对Activator.CreateInstance的调用,这比本机构造函数慢得多.

我有以下解决方法:

public static class ParameterlessConstructor<T>
    where T : new()
{
    public static T Create()
    {
        return _func();
    }

    private static Func<T> CreateFunc()
    {
        return Expression.Lambda<Func<T>>( Expression.New( typeof( T ) ) ).Compile();
    }

    private static Func<T> _func = CreateFunc();
}

// Example:
// Foo foo = ParameterlessConstructor<Foo>.Create();
Run Code Online (Sandbox Code Playgroud)

但是,为什么这个解决方案应该是必要的,这对我没有意义.

c# generics performance constructor

17
推荐指数
2
解决办法
3418
查看次数

标签 统计

c# ×1

constructor ×1

generics ×1

performance ×1