简体   繁体   English

获取属性名称C#

[英]Get property name C#

I have a class : 我有一堂课:

class Sample
{  
   ...
}

and define a property like this: 并定义如下属性:

Sample sampleParam =new Sample(...);

and have a function : 并具有以下功能:

private void Func(Sample s)
{}

and use it like: 并像这样使用它:

Func(sampleParam);

can I get the 's' name in the function? 我可以在函数中获得's'名称吗? I mean can I get "sampleParam" (the name of param)? 我的意思是我可以获取"sampleParam" (param的名称)吗?

It sounds odd; 听起来很奇怪; but I need the name of the passed param. 但我需要传递的参数名称。

and sorry for this type of asking; 对于这种询问感到抱歉; I just wanted to ask my question as simple as possible 我只是想问我的问题,尽可能简单

You should never reference variable or property names from called methods - it's bad manners and bad design (mostly the latter). 永远不要从被调用的方法中引用变量或属性名称-这是不好的礼貌和不好的设计(主要是后者)。

There is nameof operator in C# 6.0, but it wasn't designed for this . C#6.0中有nameof运算符,但不是为此设计的。

You could use expression trees, which would slightly change your syntax. 您可以使用表达式树,这会稍微改变您的语法。 If sampleParam is not a property but a variable , you can't really access it, because compiler does not store any references to that name in generated dll file. 如果sampleParam不是属性而是变量 ,则不能真正访问它,因为编译器不会在生成的dll文件中存储对该名称的任何引用。

public string GetParamName(System.Reflection.MethodInfo method,int index)
{
    string strParameterName = string.Empty;

    if (method != null && method.GetParameters().Length > index)
        strParameterName = method.GetParameters()[index].Name;

    return retVal;
}

Yes there is a way to achieve this through Reflection ... 是的,有一种方法可以通过反射实现这一目标...

I think it is not possible to get the name for a variable which value is passed to a method. 我认为不可能获得将值传递给方法的变量的名称。 But there is the compiler service CallerMemberNameAttribute which copies the name of the caller method (here the get accessor of our property Name ) to the calling method if not specified: 但是有一个编译器服务CallerMemberNameAttribute ,如果未指定,它将调用者方法的名称(这里是我们的属性Nameget访问器)复制到调用方法中:

class Person {
    static void Main(string[] args) {
        Person bart = new Person();
        bart.Name = "Bart";
        Console.ReadKey();
    }

    private string _name;
    public string Name {
        get {
            return _name;
        } set {
            _name = value;
            PropertyChanged(); //no need to fill in `Name` here! :)
        }
    }

    //automatically copy caller's name to `propertyName`, at compile time
    private void PropertyChanged([CallerMemberName] string propertyName = "") {
        object propertyValue = this.GetType().GetProperty(propertyName).GetValue(this);
        Console.WriteLine("Property '" + propertyName + "' changed the value to '" + propertyValue + "'");
    }
}

Prints: 印刷品:

Property 'Name' changed the value to 'Bart'

这并不是您所要的,但也许更接近您想要的,但是您可以看看System.Environment.StackTrace

If you mean can you get the name 'sampleParam' from INSIDE func? 如果您是说可以从INSIDE函数获得名称“ sampleParam”? The the answer is no. 答案是否定的。 There is nameof() in C#6.0 but 'sampleParam' inside not in scope inside the func. 在C#6.0中有nameof(),但内部的'sampleParam'不在函数内部。 The variable s (of type Sample) is crated and assigned a ref to sampleParam. 创建变量s(属于Sample类型),并将其分配给sampleParam的引用。

You can get the name "s" inside Func. 您可以在Func中获得名称“ s”。 You can get the name "sampleParam" in the calling class (outside Func). 您可以在调用类中(在Func之外)获得名称“ sampleParam”。

Example (available on dotnetfiddle) 示例(在dotnetfiddle上可用)

using System;

public class Program
{
    public static Sample sampleParam {get; set;} =new Sample();
    public static void Main()
    {

        Console.WriteLine($"Name of property: {nameof(sampleParam)}");
        Func(sampleParam);
    }

    private static void Func(Sample s)
    {
        Console.Write($"Name of parameter: {nameof(s)}");
    }

}

public class Sample
{

}

Output: 输出:

Name of property: sampleParam
Name of parameter: s

Now this is a rather simplistic example. 现在,这是一个非常简单的示例。 Func exists in the same class as sampleParam and there is only one property so one could derive the name but my assumption is despite your question stating it this way you are looking for a more generalized solution. Func与sampleParam存在于同一类中,并且只有一个属性,因此可以派生该名称,但是我的假设是,尽管您有这样的疑问,但您正在寻找一种更通用的解决方案。 The problem is that inside func the calling parameter name is not in scope. 问题是在func内部,调用参数名称不在范围内。 You could capture it via nameof in the calling method and pass it into func but you shouldn't that would be horrible code for a variety of reasons. 您可以在调用方法中通过nameof捕获它,并将其传递给func,但是出于各种原因,您不应该那样做太糟糕了。

As described what you are doing is intentionally building fragile tightly coupled code which is something developers work very hard to prevent. 如前所述,您正在做的是有意地构建易碎的紧密耦合代码,这是开发人员很难避免的事情。 The caller is not going to know the name of the parameter passed into func is important and shouldn't. 调用者不会知道传递给func的参数的名称很重要,并且不应该知道。 This leads me to believe this an xy problem . 这使我相信这是一个xy问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM