简体   繁体   中英

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? I mean can I get "sampleParam" (the name of 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 .

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.

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:

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? The the answer is no. There is nameof() in C#6.0 but 'sampleParam' inside not in scope inside the func. The variable s (of type Sample) is crated and assigned a ref to sampleParam.

You can get the name "s" inside Func. You can get the name "sampleParam" in the calling class (outside Func).

Example (available on 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. The problem is that inside func the calling parameter name is not in scope. 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.

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. This leads me to believe this an xy problem .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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