C# 获取变量或参数的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9801624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:55:28  来源:igfitidea点击:

get name of a variable or parameter

c#

提问by olidev

I would like to get the name of a variable or parameter:

我想获取变量或参数的名称:

For example if I have:

例如,如果我有:

var myInput = "input";

var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput

void testName([Type?] myInput)
{
   var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput
}

How can I do it in C#?

我怎样才能在 C# 中做到这一点?

采纳答案by Nikola Anusev

Pre C# 6.0 solution

Pre C# 6.0 解决方案

You can use this to get a name of any provided member:

您可以使用它来获取任何提供的成员的名称:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

获取变量名:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

获取参数名称:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

C# 6.0 及更高版本的解决方案

You can use the nameofoperator for parameters, variables and properties alike:

您可以将nameof运算符用于参数、变量和属性等:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

回答by Marc Gravell

What you are passing to GETNAMEis the valueof myInput, not the definition of myInputitself. The only way to do that is with a lambda expression, for example:

你所要传递GETNAME的是myInput,而不是定义myInput本身。唯一的方法是使用 lambda 表达式,例如:

var nameofVar = GETNAME(() => myInput);

and indeed there are examples of that available. However! This reeks of doing something very wrong. I would propose you rethink whyyou need this. It is almost certainly not a good way of doing it, and forces various overheads (the capture class instance, and the expression tree). Also, it impacts the compiler: without this the compiler might actually have chosen to remove that variable completely(just using the stack without a formal local).

并且确实有可用的示例。然而!这散发着做错事的恶臭。我建议你重新考虑为什么你需要这个。这几乎肯定不是一个好方法,并且会强制执行各种开销(捕获类实例和表达式树)。此外,它会影响编译器:如果没有这个,编译器实际上可能会选择完全删除该变量(仅使用没有正式本地的堆栈)。

回答by nawfal

Alternatively,

或者,

1) Without touching System.Reflectionnamespace,

1) 不涉及System.Reflection命名空间,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

2)下面的可以更快(从我的测试中)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

您还可以为对象的属性扩展它(可能使用扩展方法):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

您可以缓存属性值以进一步提高性能,因为属性名称在运行时不会更改。

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

根据我的口味,Expression 方法会比较慢。要一次性获取参数名称和值,请参阅我的这个答案