自 .NET 4.5(2012)以来,一些新的扩展方法出现了,来自 System.Reflection.RuntimeReflectionExtensions
类。但是,这些新方法似乎没有给我们带来什么新东西。例如:
static void Main()
{
var prop1 = typeof(string).GetProperty("Length");
var prop2 = typeof(string).GetRuntimeProperty("Length"); // extension, needs: using System.Reflection;
Console.WriteLine(prop1 == prop2);
Action a = Main;
var meth1 = a.Method;
var meth2 = a.GetMethodInfo(); // extension, needs: using System.Reflection;
Console.WriteLine(meth1 == meth2);
}
这会写两个True
。
(在这里,==
运算符被重载了,但即使使用(object)prop1 == (object)prop2
和(object)meth1 == (object)meth2
检查引用相等性,也会得到True
。)
那么这些新的公开可见方法的目的是什么呢?显然我必须忽略或误解了某些东西。
GetRuntimeProperty
只是执行与type.GetProperty(name)
相同的方法。 - Sergey Litvinov