相关疑难解决方法(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
查看次数

给定"where T:new()","new T()"在内部使用Activator.CreateInstance吗?

如果我有一个类型参数约束new():

void Foo<T>() where T : new()
{
    var t = new T();
}
Run Code Online (Sandbox Code Playgroud)

new T()内部使用该Activator.CreateInstance方法(即反射)是真的吗?

c# generics reflection activator type-constraints

14
推荐指数
1
解决办法
793
查看次数

C# - new()约束的泛型如何生成机器代码?

public T Foo<T, U>(U thing) where T : new()
{
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

当没有new()约束时,我理解它是如何工作的.JIT编译器看到T,如果它是引用类型,则使用代码的对象版本,并专门针对每个值类型的情况.

如果你有一个新的T(),它是如何工作的?它在哪里寻找?

c# generics clr

5
推荐指数
1
解决办法
91
查看次数