所以c公开了typeof
关键字,该关键字为我们提供对类型的强类型访问
var type = typeof(MyClass);
但是它不允许我们访问
methodof
或fieldof
。实际上是这样的。var method = methodof(MyClass.MyMethod);
var getProperty = methodof(MyClass.get_MyProperty)
var setProperty = methodof(MyClass.set_MyProperty)
var field = fieldof(MyClass.myField);
其他语言是否公开了此功能?
注意:发布C反射代码不是此问题的有效答案
最佳答案
如果你自己生成il,那么这是可能的。typeof(t)所做的是用ldtoken指令硬编码运行时类型句柄,然后调用type.gettypefromhandle。当我生成il时,我总是生成equiplent。下面是我编写的一些代码中的一些实用方法
/// <summary>
/// Pushes the specified member onto the evaluation stack.
/// </summary>
/// <param name="generator">The generator.</param>
/// <param name="member">The member.</param>
public static void EmitLoadMemberInfo(this ILGenerator generator, MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Method:
generator.Emit(OpCodes.Ldtoken, member as MethodInfo);
generator.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(RuntimeMethodHandle) }, null));
break;
case MemberTypes.TypeInfo:
generator.Emit(OpCodes.Ldtoken, member as Type);
generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Public | BindingFlags.Static));
break;
case MemberTypes.Field:
generator.Emit(OpCodes.Ldtoken, member as FieldInfo);
generator.Emit(OpCodes.Call, typeof(FieldInfo).GetMethod("GetFieldFromHandle", BindingFlags.Public | BindingFlags.Static));
break;
case MemberTypes.Constructor:
generator.Emit(OpCodes.Ldtoken, member as ConstructorInfo);
generator.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(RuntimeMethodHandle) }, null));
break;
default:
throw new NotSupportedException("Unsupported token type.");
}
}
我还应该提到,有一些嘲弄框架支持这一点。我举了一个例子,由于篇幅太大