C# 如何获取类属性的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/672412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:46:21  来源:igfitidea点击:

How to get name of a class property?

c#reflectionpropertiesgettype

提问by Jeff

Is there anyway I can get the name of class property IntProperty?

无论如何我可以获得类属性的名称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

Basically what I want to do is to dynamically save property name string into the database, and later on retrieve it from the database and invoke the property dynamically.

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

Seems like what I am looking for is similar to duck typing I think.

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

Thanks!

谢谢!

UPDATED:

更新:

This is the actual code. This is more like a workflow kind of thing. But each task is defined as property of a class (class is used to group tasks).

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

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."
                );
        }
    }
}

So, the code will be able to retrieve the full name of the class and property something like: namespace.ApplicationTask.SendIncompleteNotificationand save this into the database. Later on, the code will read the string and dynamically create the task and pass it into another to execute.

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

采纳答案by Jon Skeet

The result of ClassName.IntPropertyis just an integer value. As soon as it's executed and the result is returned, there's no trace of it having come from IntProperty.

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

If you're using .NET 3.5 you can use an expression tree instead, usually created via a lambda expression:

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

Expression<Func<int>> exp = () => ClassName.IntProperty;

You can then compile and execute the expression andseparately find out what it's doing (retrieving IntPropertyin this case). I'm not really sure whether this is suitable for what you want to do though.

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

If you dowork out how to save the property name in the database, then GetPropertyis the way to go on the retrieval front.

如果您确实弄清楚如何将属性名称保存在数据库中,那么这GetProperty就是检索前端的方法。

Perhaps if you could give more context in the question in terms of how you want to use this, we could help more. You've shown just an expression - if you could show it in terms of where you'd be using it, that would be great.

也许如果您可以就您想如何使用这个问题提供更多背景信息,我们可以提供更多帮助。您只展示了一个表达式 - 如果您可以根据使用它的位置来展示它,那就太好了。

EDIT: You've expanded the property, but not how it's being called. Do you needto call it directly, rather than just fetching the list of properties using Type.GetPropertiesand storing the list of property names in the database?

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

Again, if you could show the code which callsthe property, and how you want it to interact with the database, we may be able to make more progress.

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

回答by DavyR

Type objectType = this.GetType();
PropertyInfo property = objectType.GetProperty("intProperty");
System.Console.Write(property.Name);

Is this what you need?

这是你需要的吗?

回答by CMS

I think that the use of the GetPropertymethod in this case, is redundant, because you need to know the property name to call the method.

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

You could loop through your properties and extract its name:

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

foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
    string propertyName = p.Name;
    //....
}

回答by Dex

I came across this, and it seems very helpful for getting property name. (C++)

我遇到了这个,它似乎对获取属性名称很有帮助。(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;
}

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

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

回答by Ajay Bhasy

With C#6.0 you can get it by

使用 C#6.0 你可以通过

nameof(ClassName.IntProperty)