c# - 在运行时解析参数名称

标签 c# reflection anonymous-types

<分区>

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

关于c# - 在运行时解析参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/869610/

相关文章:

c# - 将 RadioButton XAML 定位在内容的中心底部

c# - 当页面向后导航到带有 MapControl 的页面时,UAP 应用程序崩溃

java - 反射可以改变字段的声明类型吗

android - 什么时候需要 kotlin Reflect lib?

c# - 合并匿名类型

c# - .NET 会受益于 "named anonymous"类型吗?

C# - 将项目从 ListView 拖到垃圾桶中?

c# - ListView 中选定索引的问题

c# - Linq 查询从对象 B 中获取与对象 A 具有相同名称和类型的属性

c# - 无法创建类型为 'Anonymous type' 的常量值