[英]CallerInfo, get name of variable passed to method (like nameof)
public void Test ()
{
string myString = "hello";
}
public void Method (string text)
{
COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello"
}
是否可以獲取傳遞給方法的變量名稱?
我想實現這一目標:
Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance");
可能嗎? 與來電者信息或類似的東西?
沒有nameof運算符?
反射的問題是,一旦編譯了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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.