无论如何,我可以获得类属性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<string> SendIncompleteNotification
{
get
{
return new Task<string>
(
a => Console.WriteLine("Sample Task")
, "This is a sample task which does nothing."
);
}
}
}
因此,代码将能够检索类和属性的全名,例如:namespace.ApplicationTask.SendIncompleteNotification
并将其保存到数据库中。稍后,代码将读取字符串并动态创建任务并将其传递给另一个任务以执行。
答案 0 :(得分:31)
使用C#6.0,你可以通过
获得它state
答案 1 :(得分:25)
我认为在这种情况下使用GetProperty方法是多余的,因为您需要知道属性名称才能调用该方法。
您可以遍历您的属性并提取其名称:
foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
string propertyName = p.Name;
//....
}
答案 2 :(得分:8)
ClassName.IntProperty
的结果只是一个整数值。一旦执行并返回结果,就没有来自IntProperty
的痕迹。
如果您使用的是.NET 3.5,则可以使用表达式树,通常通过lambda表达式创建:
Expression<Func<int>> exp = () => ClassName.IntProperty;
然后,您可以编译并执行表达式和,分别找出它正在做什么(在这种情况下检索IntProperty
)。我不确定这是否适合你想做的事。
如果你做计算出如何在数据库中保存属性名称,那么GetProperty
就是进行检索的方法。
也许如果你可以根据你想要如何使用它来提供更多关于问题的背景,我们可以提供更多帮助。你只是表达了一个表达式 - 如果你可以根据你使用它的位置来表示它,那就太棒了。
编辑:你扩展了属性,但没有扩展属性。您是否需要直接调用它,而不是仅使用Type.GetProperties
获取属性列表并将属性名称列表存储在数据库中?
同样,如果您可以显示调用属性的代码,以及您希望它与数据库交互的方式,我们可能会取得更多进展。
答案 3 :(得分:4)
Type objectType = this.GetType();
PropertyInfo property = objectType.GetProperty("intProperty");
System.Console.Write(property.Name);
这是你需要的吗?
答案 4 :(得分:0)
您可以简单地使用 nameof(ClassName.IntProperty)
它会给你“IntProperty”
答案 5 :(得分:-4)
我遇到了这个,看起来对获取属性名称非常有帮助。 (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