Why does the c# compiler emit Activator.CreateInstance when calling new in with a generic type with a new() constraint?

后端 未结 5 1529
太阳男子
太阳男子 2020-11-27 06:33

When you have code like the following:

static T GenericConstruct() where T : new()
{
    return new T();
}

The C# compiler insist

5条回答
  •  星月不相逢
    2020-11-27 07:07

    Interesting observation :)

    Here is a simpler variation on your solution:

    static T Create() where T : new()
    {
      Expression> e = () => new T();
      return e.Compile()();
    }
    

    Obviously naive (and possible slow) :)

提交回复
热议问题