这是我上一个问题的链接,它引导我找到了这个问题。C# 嵌套 foreach 循环优化 https://stackoverflow.com/questions/7729231/c-nested-foreach-loop-optimization
计算时间仍然很长,我不确定原因是什么。
object foo;
List<string> StringList = new List<string>(); // Populated by previous code
Dictionary<string, Type> assemblyTypes = RandomAssembly.GetTypes().ToDictionary(t => t.Name, t => t);
foreach (String name in StringList)
{
if (assemblyTypes.ContainsKey(name))
{
// Create an instance of the matching class and add it
// to the appropriate lists.
Type at = assemblyTypes[name];
foo = Activator.CreateInstance(at);
ArbitraryList1.Add(foo);
}
}
如果计算时间明显很慢,我猜您会多次调用此代码,并且会更新许多在编译时不太了解的对象。
而不是将课程保留在Dictionary<string, type>
并打电话CreateInstance
你想保留他们的构造函数的字典Dictionary<string, ConstructorInfo>
所以你可以直接调用它们,而不必每次都通过反射来查找。
这样,您只需调用 AssemblyConstructors[Name].Invoke() 即可创建该类的新实例。
这样你只需要使用一次反射来找到构造函数。
// keep a dictionary of constructors (instead of the types)
var Constructors = new Dictionary<string, ConstructorInfo>();
// add this class to this dictionary
Type t = typeof(SomeClass);
string name = t.Name;
Constructors[name] = t.GetConstructors()[0]; // use reflection only once here, afterwards we reuse the reflected info
// new up an instance
var o = Constructors[name].Invoke(new object[] {});
我认为第一个构造函数将是无参数的。否则尝试类似的东西t.GetConstructors().Where(x => x.GetParameters().Count() == 0).First();
这是我知道的最快简单的方法,因为显然你无法获得构造函数的委托 https://stackoverflow.com/questions/1600712/a-constructor-as-a-delegate-is-it-possible-in-c.
如果您自己编写新的类,则可以拥有一个公共基类或接口,并带有创建基类或接口的方法,这样您就可以保留对该构造函数的委托,这甚至更快。
这个帖子 http://blogs.msdn.com/b/haibo_luo/archive/2005/11/17/494009.aspx还有一些有趣的想法需要优化much更远。如果你想快速做到这一点,你可以。几乎和打电话一样快new KnownClass()
祝你好运,
GJ
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)