use*_*267 17 c# generics performance constructor
如果您有以下代码:
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)
但是,为什么这个解决方案应该是必要的,这对我没有意义.
这很可能是因为不清楚T是值类型还是引用类型.在非通用场景中创建这两种类型会产生非常不同的IL.面对这种模糊性,C#被迫使用通用的类型创建方法.Activator.CreateInstance符合要求.
快速实验似乎支持这一想法.如果键入以下代码并检查IL,它将使用initobj而不是CreateInstance,因为类型没有歧义.
static void Create<T>()
where T : struct
{
var x = new T();
Console.WriteLine(x.ToString());
}
Run Code Online (Sandbox Code Playgroud)
将其切换为类和new()约束仍会强制激活Activator.CreateInstance.
归档时间: |
|
查看次数: |
3418 次 |
最近记录: |