首页 > 解决方案 > 不使用nameof获取传递的方法名

问题描述

声明一个方法很容易,它将方法名称作为字符串:

public void DoSomethingWithMethodName(string methodName)
{
    // Do something with the method name here.
}

并将其称为:

DoSomethingWithMethodName(nameof(SomeClass.SomeMethod));

我想摆脱nameof并调用其他一些方法:

DoSomethingWithMethod(SomeClass.SomeMethod);

然后能够获得与上面示例中相同的方法名称。Expression它“感觉”可以使用一些和/或Func巫术来做到这一点。问题是DoSomethingWithMethod它应该有什么签名以及它应该做什么!

=====================================

这个问题似乎引起了很多混乱,答案假设我没有问。这是我的目标但无法正确的提示。这是针对一些不同的问题(我有一个解决方案)。我可以声明:

    private async Task CheckDictionary(Expression<Func<LookupDictionary>> property, int? expectedIndex = null)
    {
        await RunTest(async wb =>
        {
            var isFirst = true;

            foreach (var variable in property.Compile().Invoke())
            {
                // Pass the override value for the first index.
                await CheckSetLookupIndex(wb, GetPathOfProperty(property), variable, isFirst ? expectedIndex : null);
                isFirst = false;
            }
        });
    }

GetPathOfProperty来自: https ://www.automatetheplanet.com/get-property-names-using-lambda-expressions/ 和完全限定的属性名称

然后使用:

    [Fact]
    public async Task CommercialExcelRaterService_ShouldNotThrowOnNumberOfStories() =>
        await CheckDictionary(() => EqNumberOfStories, 2);

哪里EqNumberOfStories是:

    public static LookupDictionary EqNumberOfStories { get; } = new LookupDictionary(new Dictionary<int, string>
    {
        { 1, "" },
        { 2, "1 to 8" },
        { 3, "9 to 20" },
        { 4, "Over 20" }
    });

如您所见,我正在传递一个属性,然后“展开”它以找到源。我想做同样的事情,但设置更简单,如上所述。

标签: c#lambdaexpressionfunc

解决方案


您可以使用[CallerMemberName]来获取调用方法的名称。

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

在上面的示例中,示例memberName参数将被分配 value DoProcessing

样本输出

消息:发生了一些事情。

成员名称:DoProcessing

源文件路径:C:\Users\user\AppData\Local\Temp\LINQPad5_osjizlla\query_gzfqkl.cs

源行号:37

https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx


推荐阅读