C# 获取参数名称的方法

Die*_*go 0 c#

在C#中如何获取方法调用的参数名称?

例子:

public static void PrintList (List<string> list)
{
    Console.WriteLine("\n");
    foreach (var item in list)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("\n");
}

PrintList(oxygenList);
Run Code Online (Sandbox Code Playgroud)

我需要打印的方法:

氧气清单

谢谢。

Mat*_*son 5

如果您使用的是 C# 10 或更高版本,则可以使用新CallerArgumentExpression属性来实现此目的:

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

public static class Program
{
    public static void Main()
    {
        List<string> oxygenList = new List<string> { "A", "B", "C" };
        PrintList(oxygenList);
    }

    public static void PrintList(List<string> list, [CallerArgumentExpression("list")] string? name = null)
    {
        Console.WriteLine("Argument name = " + name); // Prints "Argument name = oxygenList
        Console.WriteLine("\n");

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,请注意,这给出了调用该方法时使用的表达式- 因此,如果您使用以下代码调用它:

public static void Main()
{
    PrintList(getOxygenList());
}

public static List<string> getOxygenList()
{
    return new List<string> { "A", "B", "C" };
}
Run Code Online (Sandbox Code Playgroud)

传递的值name将是“getOxygenList()”。

它必须像这样工作,因为表达式可以用于参数 - 它不限于简单的变量名称。