解决在运行时参数名称 [英] Resolving a parameter name at runtime
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp\">Finding变量名称传递给函数在C#
块引用>在C#中,有没有办法(更简洁越好)在运行时解析参数的名称?
例如,在下面的方法,如果您重命名方法参数,你也必须记住要更新字符串传递给ArgumentNullException。
公共无效纬(对象资源)
{
如果(资源== NULL)
{
抛出新的ArgumentNullException(资源);
} // ..
}
解决方案的一种方式:
静态无效的主要(字串[] args)
{
Console.WriteLine(名称为{0}'的GetName(新{} ARGS));
到Console.ReadLine();
}这code还需要一个支持功能:
静态字符串的GetName&LT; T&GT;(T项目),其中T:类
{
VAR性能= typeof运算(T).GetProperties();
Enforce.That(properties.Length == 1);
返回性能[0] .Name点;
}基本上,code ++工程,通过定义一个新的匿名类型与包括谁是你想要的名称参数的一个属性。的GetName(),然后使用反射来提取属性的名称。
在这里有更多的细节:<一href=\"http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html\">http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html
Possible Duplicate:
Finding the Variable Name passed to a Function in C#In C#, is there a way (terser the better) to resolve the name of a parameter at runtime?
For example, in the following method, if you renamed the method parameter, you'd also have to remember to update the string literal passed to ArgumentNullException.
public void Woof(object resource) { if (resource == null) { throw new ArgumentNullException("resource"); } // .. }
解决方案One way:
static void Main(string[] args) { Console.WriteLine("Name is '{0}'", GetName(new {args})); Console.ReadLine(); }
This code also requires a supporting function:
static string GetName<T>(T item) where T : class { var properties = typeof(T).GetProperties(); Enforce.That(properties.Length == 1); return properties[0].Name; }
Basically the code works by defining a new Anonymous Type with a single Property consisting of the parameter who's name you want. GetName() then uses reflection to extract the name of that Property.
There are more details here: http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html
这篇关于解决在运行时参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!