C# - 你如何获得一个变量的名称,因为它是在其声明中物理类型? [英] c# - How do you get a variable's name as it was physically typed in its declaration?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp\">Finding变量名称传递给函数在C#
下面的类包含字段的城市。
The class below contains the field city.
我需要动态地确定字段的名字,因为它是在类声明类型
即我需要从对象城市的一个实例得到字符串城市。
I need to dynamically determine the field's name as it is typed in the class declaration i.e. I need to get the string "city" from an instance of the object city.
我曾尝试通过检查其DoSomething的(类型做到这一点),但在调试器检查类型的内容时,无法找到它。
I have tried to do this by examining its Type in DoSomething() but can't find it when examining the contents of the Type in the debugger.
这可能吗?
public class Person
{
public string city = "New York";
public Person()
{
}
public void DoSomething()
{
Type t = city.GetType();
string field_name = t.SomeUnkownFunction();
//would return the string "city" if it existed!
}
}
有些人在下面他们的答案都问我为什么要这么做。
这里的原因。
Some people in their answers below have asked me why I want to do this. Here's why.
在我的现实世界的情况,上面有城市的自定义属性。
In my real world situation, there is a custom attribute above city.
[MyCustomAttribute("param1", "param2", etc)]
public string city = "New York";
我需要在其他code此属性。
要获得属性,我使用反射。
而在反射code我需要输入字符串城市
I need this attribute in other code. To get the attribute, I use reflection. And in the reflection code I need to type the string "city"
MyCustomAttribute attr;
Type t = typeof(Person);
foreach (FieldInfo field in t.GetFields())
{
if (field.Name == "city")
{
//do stuff when we find the field that has the attribute we need
}
}
现在这不是类型安全的。
如果我在我的人字段声明中改变了变量城市到workCity这条线会失败,除非我知道更新字符串
Now this isn't type safe. If I changed the variable "city" to "workCity" in my field declaration in Person this line would fail unless I knew to update the string
if (field.Name == "workCity")
//I have to make this change in another file for this to still work, yuk!
{
}
所以我试图找到一些方式来传递字符串这个code,而不实际打字吧。
So I am trying to find some way to pass the string to this code without physically typing it.
是的,我可以宣布它作为一个字符串中的人(或类似的东西)不变,但将仍然两次打字吧。
Yes, I could declare it as a string constant in Person (or something like that) but that would still be typing it twice.
唷!这是很难解释!
感谢
感谢所有谁回答了这个*很多*。这给我发了一条新的道路上更好地理解拉姆达前pressions。它创造了一个新的问题。
Thanks to all who answered this * a lot*. It sent me on a new path to better understand lambda expressions. And it created a new question.
推荐答案
也许你需要这个。工作正常。
Maybe you need this. Works fine.
我发现这个这里。
static void Main(string[] args)
{
var domain = "matrix";
Check(() => domain);
Console.ReadLine();
}
static void Check<T>(Expression<Func<T>> expr)
{
var body = ((MemberExpression)expr.Body);
Console.WriteLine("Name is: {0}", body.Member.Name);
Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)
.GetValue(((ConstantExpression)body.Expression).Value));
}
输出将是:
Name is: 'domain'
Value is: 'matrix'
这篇关于C# - 你如何获得一个变量的名称,因为它是在其声明中物理类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!