我试图从WinRT中的操作中获得方法名称,其中Action。方法不可用。到目前为止,我有这个:
public class Test2
{
public static Action<int> TestDelegate { get; set; }
private static string GetMethodName(Expression<Action<int>> e)
{
Debug.WriteLine("e.Body.NodeType is {0}", e.Body.NodeType);
MethodCallExpression mce = e.Body as MethodCallExpression;
if (mce != null)
{
return mce.Method.Name;
}
return "ERROR";
}
public static void PrintInt(int x)
{
Debug.WriteLine("int {0}", x);
}
public static void TestGetMethodName()
{
TestDelegate = PrintInt;
Debug.WriteLine("PrintInt method name is {0}", GetMethodName(x => PrintInt(x)));
Debug.WriteLine("TestDelegate method name is {0}", GetMethodName(x => TestDelegate(x)));
}
}
当我调用TestGetMethodName()时,我得到这样的输出:
e.Body.NodeType is Call
PrintInt method name is PrintInt
e.Body.NodeType is Invoke
TestDelegate method name is ERROR
目标是获取分配给TestDelegate的方法的名称。调用"GetMethodName(x => PrintInt(x))"只是为了证明我做的至少是部分正确的。我怎样才能让它告诉我"TestDelegate方法名是PrintInt"?
答案比我想的要简单得多。它就是TestDelegate.GetMethodInfo(). name。不需要GetMethodName函数。我没有"使用系统"。反射,还有委托。GetMethodInfo没有出现在智能感知中,我不知何故在文档中错过了它。感谢HappyNomad弥合了这一差距。
工作代码为:
public class Test2
{
public static Action<int> TestDelegate { get; set; }
public static void PrintInt(int x)
{
Debug.WriteLine("int {0}", x);
}
public static void TestGetMethodName()
{
TestDelegate = PrintInt;
Debug.WriteLine("TestDelegate method name is {0}", TestDelegate.GetMethodInfo().Name);
}
}
private static string GetMethodName( Expression<Action<int>> e )
{
Debug.WriteLine( "e.Body.NodeType is {0}", e.Body.NodeType );
MethodCallExpression mce = e.Body as MethodCallExpression;
if ( mce != null ) {
return mce.Method.Name;
}
InvocationExpression ie = e.Body as InvocationExpression;
if ( ie != null ) {
var me = ie.Expression as MemberExpression;
if ( me != null ) {
var prop = me.Member as PropertyInfo;
if ( prop != null ) {
var v = prop.GetValue( null ) as Delegate;
return v.Method.Name;
}
}
}
return "ERROR";
}