<分区>
Possible Duplicate:
Finding the Variable Name passed to a Function in C#
下面的类包含字段城市。
我需要动态确定在类声明中键入的字段名称 即我需要从对象 city 的实例中获取字符串“city”。
我试图通过在 DoSomething() 中检查它的类型来做到这一点,但在调试器中检查类型的内容时找不到它。
这可能吗?
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!
}
}
有些人在下面的回答中问我为什么要这样做。 原因如下。
在我的现实世界中,城市上方有一个自定义属性。
[MyCustomAttribute("param1", "param2", etc)]
public string city = "New York";
我在其他代码中需要这个属性。 为了获取属性,我使用了反射。 在反射代码中,我需要输入字符串“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
}
}
现在这不是类型安全的。 如果我在 Person 的字段声明中将变量“city”更改为“workCity”,除非我知道更新字符串,否则此行将失败
if (field.Name == "workCity")
//I have to make this change in another file for this to still work, yuk!
{
}
所以我试图找到一些方法来将字符串传递给此代码而无需实际键入它。
是的,我可以将它声明为 Person 中的字符串常量(或类似的东西),但仍然需要输入两次。
呸!这很难解释!!
谢谢
感谢所有回答这个问题的人*很多*。它让我走上了一条更好地理解 lambda 表达式的新道路。它产生了一个新问题。