我正在编写一个系统,需要我使用反射获取对象属性的值。这个项目是为了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
我不喜欢这个有两个原因:
- Casting is for potters, generics is for programmers
- It obviously creates garbage every time I have to get a primitive value and it gets boxed.
有没有一种通用的方法来获取属性的值,不会装箱原始类型?
回应 Jon 的答案,从他的博客中盗用的这个代码不会导致分配,问题已解决:
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");
}