2014-12-17 2 views
0
public void Test() 
{ 
    string myString = "hello"; 
} 

public void Method (string text) 
{ 
    COnsole.WriteLine (... + " : " + text); // should print "myString : hello" 
} 

메서드에 전달되는 변수의 이름을 가져올 수 있습니까?CallerInfo, 메서드에 전달 된 변수의 이름을 가져옵니다 (예 : nameof)

나는이 달성하고자하는

:

Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance"); 

이 가능를? 발신자 정보 또는 비슷한 정보가 있습니까?

nameof 연산자가 없습니까?

+1

. callsite를 변경하여 표현 트리를 남용 할 수 있습니다. – SLaks

답변

2

C# 코드를 컴파일하고 나면 더 이상 변수 이름을 갖지 않습니다. 이를 수행하는 유일한 방법은 변수를 클로저로 승격시키는 것입니다. 그러나 함수에 새 변수 이름을 출력하기 때문에 수행중인 함수에서 변수를 호출 할 수 없습니다. 이것은 작동합니다 :

using System; 
using System.Linq.Expressions; 

public class Program 
{ 
    public static void Main() 
    { 
     string myString = "My Hello string variable"; 

     // Prints "myString : My Hello String Variable 
     Console.WriteLine("{0} : {1}", GetVariableName(() => myString), myString); 
    } 

    public static string GetVariableName<T>(Expression<Func<T>> expr) 
    { 
     var body = (MemberExpression)expr.Body; 

     return body.Member.Name; 
    } 
} 

하지만 이것은 작동하지 않을 것입니다 :

완전히 불가능
using System; 
using System.Linq.Expressions; 

public class Program 
{ 
    public static void Main() 
    { 
     string myString = "test"; 

     // This will print "myVar : test" 
     Method(myString); 
    } 

    public static void Method(string myVar) 
    { 
     Console.WriteLine("{0} : {1}", GetVariableName(() => myVar), myVar); 
    } 

    public static string GetVariableName<T>(Expression<Func<T>> expr) 
    { 
     var body = (MemberExpression)expr.Body; 

     return body.Member.Name; 
    } 
} 
+0

메가 오버 헤드 x-처럼 보입니다.) 고마워요. – zgnilec

관련 문제