Mar*_*tin 5 c# reflection garbage
我正在编写一个系统,它要求我获取对象中的属性值,最好使用反射。这个项目是针对 xbox360 的,它在紧凑的框架上运行,因此有一个缓慢的垃圾收集器 - 这意味着我避免分配是绝对重要的!
我发现做到这一点的唯一方法是:
Foo Something; //an object I want to get data from
PropertyInfo p; //get this via reflection for the property I want
object value = p.GetGetmethod().Invoke(Something, null);
//Now I have to cast value into a type that it should be
Run Code Online (Sandbox Code Playgroud)
我不喜欢这个有两个原因:
是否有一些通用方法可以从属性中获取值,并且不会对基元进行装箱?
编辑::为了回应 Jons 的回答,从他的博客中窃取的代码不会导致分配,问题已解决:
String methodName = "IndexOf";
Type[] argType = new Type[] { typeof(char) };
String testWord = "TheQuickBrownFoxJumpedOverTheLazyDog";
MethodInfo method = typeof(string).GetMethod(methodName, argType);
Func<char, int> converted = (Func<char, int>)Delegate.CreateDelegate
(typeof(Func<char, int>), testWord, method);
int count = GC.CollectionCount(0);
for (int i = 0; i < 10000000; i++)
{
int l = converted('l');
if (GC.CollectionCount(0) != count)
Console.WriteLine("Collect");
}
Run Code Online (Sandbox Code Playgroud)
一种替代方法是使用 getter 方法创建委托Delegate.CreateDelegate- 我不知道 Xbox 使用的紧凑框架版本是否支持这一点。
我有一篇博文,Delegate.CreateDelegate您可能会觉得有用 - 但同样,您需要了解其中有多少内容适用于 Xbox。