在运行时解析参数名称 [英] Resolving a parameter name at runtime

查看:21
本文介绍了在运行时解析参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在C#中查找传递给函数的变量名

在 C# 中,有没有办法(越简洁越好)在运行时解析参数的名称?

In C#, is there a way (terser the better) to resolve the name of a parameter at runtime?

例如,在下面的方法中,如果您重命名了方法参数,您还必须记住更新传递给 ArgumentNullException 的字符串文字.

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");
        }

        // ..
    }

推荐答案

一种方式:

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;
}

基本上,代码的工作原理是定义一个新的匿名类型,该类型具有一个由您想要的参数名组成的属性.GetName() 然后使用反射来提取该属性的名称.

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.

这里有更多详细信息:http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html

这篇关于在运行时解析参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆