gwi*_*dry 13 c# reflection performance runtime dynamic
在.NET 4中创建在运行时确定的类型实例的最佳方法是什么?
我有一个实例方法,虽然作用于BaseClass对象可能会被其派生类的实例调用.我需要创建this
与方法中相同类型的另一个实例.为每个派生类重载Method是不切实际的,因为它相当复杂,并且更有效地保持单个实现.
public class BaseClass
{
//constructors + properties + methods etc
public SomeMethod()
{
//some code
DerivedClass d = new DerivedClass(); //ideally determine the DerivedClass type at run-time
}
}
Run Code Online (Sandbox Code Playgroud)
我已经阅读了一些关于反射或使用动态关键字但我没有这些经验.
Ser*_*-Tm 22
在运行时重复创建实例的性能的最佳方式是编译表达式:
static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(
Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
).Compile();
X x = YCreator();
Run Code Online (Sandbox Code Playgroud)
统计(2012年):
Iterations: 5000000
00:00:00.8481762, Activator.CreateInstance(string, string)
00:00:00.8416930, Activator.CreateInstance(type)
00:00:06.6236752, ConstructorInfo.Invoke
00:00:00.1776255, Compiled expression
00:00:00.0462197, new
Run Code Online (Sandbox Code Playgroud)
统计(2015年,.net 4.5,x64):
Iterations: 5000000
00:00:00.2659981, Activator.CreateInstance(string, string)
00:00:00.2603770, Activator.CreateInstance(type)
00:00:00.7478936, ConstructorInfo.Invoke
00:00:00.0700757, Compiled expression
00:00:00.0286710, new
Run Code Online (Sandbox Code Playgroud)
统计(2015年,.net 4.5,x86):
Iterations: 5000000
00:00:00.3541501, Activator.CreateInstance(string, string)
00:00:00.3686861, Activator.CreateInstance(type)
00:00:00.9492354, ConstructorInfo.Invoke
00:00:00.0719072, Compiled expression
00:00:00.0229387, new
Run Code Online (Sandbox Code Playgroud)
完整代码:
public static X CreateY_New()
{
return new Y();
}
public static X CreateY_CreateInstance()
{
return (X)Activator.CreateInstance(typeof(Y));
}
public static X CreateY_CreateInstance_String()
{
return (X)Activator.CreateInstance("Program", "Y").Unwrap();
}
static readonly System.Reflection.ConstructorInfo YConstructor =
typeof(Y).GetConstructor(Type.EmptyTypes);
static readonly object[] Empty = new object[] { };
public static X CreateY_Invoke()
{
return (X)YConstructor.Invoke(Empty);
}
static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(
Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))
).Compile();
public static X CreateY_CompiledExpression()
{
return YCreator();
}
static void Main(string[] args)
{
const int iterations = 5000000;
Console.WriteLine("Iterations: {0}", iterations);
foreach (var creatorInfo in new []
{
new {Name = "Activator.CreateInstance(string, string)", Creator = (Func<X>)CreateY_CreateInstance},
new {Name = "Activator.CreateInstance(type)", Creator = (Func<X>)CreateY_CreateInstance},
new {Name = "ConstructorInfo.Invoke", Creator = (Func<X>)CreateY_Invoke},
new {Name = "Compiled expression", Creator = (Func<X>)CreateY_CompiledExpression},
new {Name = "new", Creator = (Func<X>)CreateY_New},
})
{
var creator = creatorInfo.Creator;
var sum = 0;
for (var i = 0; i < 1000; i++)
sum += creator().Z;
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < iterations; ++i)
{
var x = creator();
sum += x.Z;
}
stopwatch.Stop();
Console.WriteLine("{0}, {1}", stopwatch.Elapsed, creatorInfo.Name);
}
}
public class X
{
public X() { }
public X(int z) { this.Z = z; }
public int Z;
}
public class Y : X { }
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 10
您正在寻找Activator.CreateInstance
(还有其他重载,例如这个接受构造函数参数的重载).所以你可以写
var anotherOneLikeMe = Activator.CreateInstance(this.GetType());
Run Code Online (Sandbox Code Playgroud)
这里可能存在一个问题,因为anotherOneLikeMe
它将被输入为object
,所以除非你打算将它转换为一个公共基类(例如BaseClass
在你的例子中),否则你可以用它做多少.
我知道这被标记为反射,但我通常认为反射是出于性能和复杂性原因的最后手段。在某些情况下,您的设计/使用需要反思;但是,我将提供一些替代方案供考虑:
使用工厂Func
:
public void SomeMethod(Func<BaseClass> createDerived)
{
BaseClass d = createDerived();
}
Run Code Online (Sandbox Code Playgroud)
使您的方法使用受约束的泛型类型:
public void SomeMethod<TDerived>() where TDerived : BaseClass, new()
{
TDerived d = new TDerived();
}
Run Code Online (Sandbox Code Playgroud)
在幕后,这最后一个替代方案Activator.CreateInstance
如其他人所建议的那样使用。我更喜欢最后一种而不是反射,因为它们都需要一个无参数构造函数,但是编译器强制要求派生类型必须具有一个无参数构造函数,而反射方法会导致运行时异常。