변수 또는 매개 변수의 이름 가져 오기 [중복]
중복 가능성 :
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
것은 자신 의 정의가 아니라의 값 입니다 . 이를 수행하는 유일한 방법은 람다 식을 사용하는 것입니다. 예를 들면 다음과 같습니다.myInput
myInput
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
'developer tip' 카테고리의 다른 글
Spring MVC에서 현재 URL을 얻는 가장 좋은 방법은 무엇입니까? (0) | 2020.09.18 |
---|---|
중재자 대 관찰자 객체 지향 디자인 패턴 (0) | 2020.09.18 |
서명되지 않은 데이터 유형은 무엇입니까? (0) | 2020.09.18 |
객체가 Python에서 파일과 유사한 지 확인 (0) | 2020.09.18 |
파이썬에서 특정 길이로 난수를 생성하는 방법 (0) | 2020.09.18 |