Possible Duplicate:
Finding the Variable Name passed to a Function in C#
在 C# 中,有没有一种方法(越简洁越好)在运行时解析参数的名称?
例如,在下面的方法中,如果您重命名了方法参数,您还必须记住更新传递给 ArgumentNullException 的字符串文字。
public void Woof(object resource)
{
if (resource == null)
{
throw new ArgumentNullException("resource");
}
// ..
}
一种方式:
static void Main(string[] args)
{
Console.WriteLine("Name is '{0}'", GetName(new {args}));
Console.ReadLine();
}
此代码还需要一个支持函数:
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
Enforce.That(properties.Length == 1);
return properties[0].Name;
}
基本上,该代码通过定义一个新的匿名类型来工作,该类型具有一个属性,该属性由您想要的参数名称组成。 GetName() 然后使用反射来提取该属性的名称。
这里有更多详细信息:http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html