【发布时间】:2011-06-20 02:23:15
【问题描述】:
如何获取字符串名称的名称而不是字符串的值
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#