【问题标题】:C# get string name's name [duplicate]C#获取字符串名称的名称[重复]
【发布时间】:2011-06-20 02:23:15
【问题描述】:

可能重复:
How to get variable name using reflection?

如何获取字符串名称的名称而不是字符串的值

string MyString = "";
Response.Write(MyString.GetType().Name);//Couldn't get the string name not the value of the string

结果应该显示回字符串名称“MyString”

我找到了一些建议的代码并重写它以使其更短,但仍然不太喜欢它。

static string VariableName<T>(T item) where T : class
{
    return typeof(T).GetProperties()[0].Name;
}

Response.Write(VariableName(new { MyString })); 我正在寻找另一种使其更短的方法,如下所示,但没有如何使用转换当前类,所以我可以在同一行中使用它们

  Response.Write( typeof(new { MyString }).GetProperties()[0].Name);

【问题讨论】:

  • 不,不应该。答案很快就会告诉你原因。
  • 您可以使用反射,但您有什么特别的理由要这样做吗?
  • 这篇博文中有几种方法:abdullin.com/journal/2008/12/13/…
  • 只是想让重命名动态变量名更容易 HttpUtility.ParseQueryString(MyString)[MyString]

标签: c#


【解决方案1】:

虽然 Marcelo 的回答(以及链接到“重复”问题)将解释如何做你所追求的,快速解释为什么你的代码不起作用。

GetType() 完全按照它所说的做:它获取调用它的对象的Type。在您的情况下,它将返回System.String,这是您的变量 MyString 引用的对象的Type。因此,您的代码实际上将打印 Type.Name,而不是变量的名称(这是您真正想要的)。

【讨论】:

  • 我已经把课程缩短了很多,但我不太喜欢它。 static string VariableNameName(T item) where T : class { return typeof(T).GetProperties()[0].Name; } ///这里是如何使用它 var MyString = ""; Response.Write(VariableNameName(new { MyString }));我想让它像下面这样更短,但还不知道如何使用这个 LINQ。 Response.Write(typeof(new { MyString }).GetProperties()[0].Name);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 2020-05-05
相关资源
最近更新 更多