如何获取类属性的名称?

无论如何我可以得到类属性IntProperty的名称?

 public class ClassName { public static int IntProperty { get { return 0; } } } //something like below but I want to get the string of "IntProperty" ClassName.IntProperty.GetType().Name 

基本上我想要做的是动态地将属性名称字符串保存到数据库中,稍后从数据库中检索它并动态调用属性。

好像我正在寻找的东西类似于我认为的鸭子打字。

谢谢!

更新:

这是实际的代码。 这更像是一种工作流程。 但是每个任务都被定义为类的属性(类用于对任务进行分组)。

 public class ApplicationTask { public static Task SendIncompleteNotification { get { return new Task ( a => Console.WriteLine("Sample Task") , "This is a sample task which does nothing." ); } } } 

因此,代码将能够检索类和属性的全名,例如: namespace.ApplicationTask.SendIncompleteNotification并将其保存到数据库中。 稍后,代码将读取字符串并动态创建任务并将其传递给另一个任务以执行。

ClassName.IntProperty的结果只是一个整数值。 一旦执行并返回结果,就没有来自IntProperty

如果您使用的是.NET 3.5,则可以使用表达式树,通常通过lambda表达式创建:

 Expression> exp = () => ClassName.IntProperty; 

然后,您可以编译并执行表达式, 分别找出它正在做什么(在这种情况下检索IntProperty )。 我不确定这是否适合你想做的事情。

如果您确实如何在数据库中保存属性名称,那么GetProperty是继续检索前进的方法。

也许如果你可以根据你想要如何使用它来提供更多关于问题的背景,我们可以提供更多帮助。 你只是表达了一个表达方式 – 如果你可以根据你使用它的方式显示它,那就太好了。

编辑:你扩展了属性,但没有扩展属性。 您是否需要直接调用它,而不是仅使用Type.GetProperties获取属性列表并将属性名称列表存储在数据库中?

同样,如果您可以显示调用该属性的代码,以及您希望它如何与数据库交互,我们可能会取得更多进展。

使用C#6.0,您可以获得它

 nameof(ClassName.IntProperty) 

我认为在这种情况下使用GetProperty方法是多余的,因为您需要知道属性名称来调用该方法。

您可以遍历您的属性并提取其名称:

 foreach (PropertyInfo p in typeof(ClassName).GetProperties()) { string propertyName = p.Name; //.... } 
 Type objectType = this.GetType(); PropertyInfo property = objectType.GetProperty("intProperty"); System.Console.Write(property.Name); 

这是你需要的吗?

我遇到了这个,看起来对于获取属性名称非常有帮助。 (C ++)

 #define getVarName(varName,holder) sprintf(holder, "%s", #varName) int main() { int var = 100; // just any type of identifier char name[100]; // it will get the variables name getVarName(var, name); puts(name); return 0; } 

参考:http: //zobayer.blogspot.com/2010/05/c-fun-get-variables-name.html