developer tip

변수 또는 매개 변수의 이름 가져 오기

copycodes 2020. 9. 18. 08:20
반응형

변수 또는 매개 변수의 이름 가져 오기 [중복]


중복 가능성 :
C #의 함수에 전달 된 변수 이름 찾기

변수 또는 매개 변수의 이름을 얻고 싶습니다.

예를 들어 다음과 같은 경우 :

var myInput = "input";

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

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

C #에서 어떻게 할 수 있습니까?


C # 6.0 이전 솔루션

이를 사용하여 제공된 구성원의 이름을 가져올 수 있습니다.

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

변수 이름을 얻으려면 :

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

매개 변수의 이름을 얻으려면 :

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

C # 6.0 이상 솔루션

매개 변수, 변수 및 속성에 대해 모두 nameof 연산자를 사용할 수 있습니다 .

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

당신이 전달하는 GETNAME것은 자신 의 정의가 아니라의 입니다 . 이를 수행하는 유일한 방법은 람다 식을 사용하는 것입니다. 예를 들면 다음과 같습니다.myInputmyInput

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 why you 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).


Alternatively,

1) Without touching System.Reflection namespace,

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)

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

참고URL : https://stackoverflow.com/questions/9801624/get-name-of-a-variable-or-parameter

반응형