本文介绍了鉴于"其中T:新的()&QUOT ;,确实"新T()"使用Activator.CreateInstance内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a type parameter constraint new():

void Foo<T>() where T : new()
{
    var t = new T();
}



这是真的,新T()将在内部使用的 Activator.CreateInstance 法(即反射)?

Is it true that new T() will internally use the Activator.CreateInstance method (i.e. reflection)?

推荐答案

是的,这是事实。 修改2:这里是怎样的一个很好的解释,为什么

Yes, this is true. Edit 2: Here's a good explanation of the how and why.

有关验证我整理了以下方法:

For verification I compiled the following method:

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

这是生成的IL时与C#编译器在.NET 3.5编译SP1:

And this is the generated IL when compiled with the C# compiler in .NET 3.5 SP1:

.method public hidebysig static !!T Create<.ctor T>() cil managed
{
    .maxstack 2
    .locals init (
        [0] !!T local,
        [1] !!T local2)
    L_0000: ldloca.s local
    L_0002: initobj !!T
    L_0008: ldloc.0
    L_0009: box !!T
    L_000e: brfalse.s L_001a
    L_0010: ldloca.s local2
    L_0012: initobj !!T
    L_0018: ldloc.1
    L_0019: ret
    L_001a: call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
    L_001f: ret
}

编辑:的C#4编译器将创建略有不同,但大同小异,代码:

The C# 4 compiler creates slightly different, but similar, code:

.method public hidebysig static !!T Create<.ctor T>() cil managed
{
    .maxstack 2
    .locals init (
        [0] !!T CS$1$0000,
        [1] !!T CS$0$0001)
    L_0000: nop
    L_0001: ldloca.s CS$0$0001
    L_0003: initobj !!T
    L_0009: ldloc.1
    L_000a: box !!T
    L_000f: brfalse.s L_001c
    L_0011: ldloca.s CS$0$0001
    L_0013: initobj !!T
    L_0019: ldloc.1
    L_001a: br.s L_0021
    L_001c: call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
    L_0021: stloc.0
    L_0022: br.s L_0024
    L_0024: ldloc.0
    L_0025: ret
}

在的情况下,值类型不使用催化剂,但仅返回默认(T)值,否则它调用 Activator.CreateInstance 方法。

In the case of a value type it doesn't use the activator but just returns the default(T) value, otherwise it invokes the Activator.CreateInstance method.

这篇关于鉴于&QUOT;其中T:新的()&QUOT ;,确实&QUOT;新T()&QUOT;使用Activator.CreateInstance内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:46