我知道过早的优化是所有邪恶的母亲.但是,我正在定义一个泛型方法,它使用Reflection来检索其泛型类型的元数据,并想知道是否typeof(T)多次调用,如下面的代码片段所示:
private static Dictionary<Type, PropertyInfo[]> elementProperties;
private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
PropertyInfo[] properties;
if (elementProperties.ContainsKey(typeof(T)))
properties = elementProperties[typeof(T)];
else
properties = elementProperties[typeof(T)] = typeof(T).GetProperties();
// more code...
}
Run Code Online (Sandbox Code Playgroud)
...比将类型对象存储到变量中的效率低,如下面的代码片段所示:
private static Dictionary<Type, PropertyInfo[]> elementProperties;
private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
PropertyInfo[] properties;
Type type = typeof(T);
if (elementProperties.ContainsKey(type))
properties = elementProperties[type];
else
properties = elementProperties[type] = type.GetProperties();
// more code...
}
Run Code Online (Sandbox Code Playgroud)
...?
如果我正确理解编译器理论(我认为我这样做),这个问题可以简化为以下问题:
当JIT编译器实例化泛型类型时,它是否替换了[无论MSIL表示typeof(T)形式]的每个实例...
c# ×1