简体   繁体   中英

c# Full Name of Property in Class

I have a class

public class MyCoolProp
{
    public string FullName {get;set;}
}

and in another Class i have this as Property:

public class MyMainClass
{
    public MyCoolProp coolprop {get;set;}

    public void DoSomething()
    {
        MessageBox.Show(nameof(coolprop.FullName));
    }
}

The Actual Result is: "Fullname"

But i want a combination like this: "coolprop.FullName"

i dont want to do something like this:

nameof(coolprop) + "." + nameof(coolprop.FullName);

Maybe its possible in an extension?

If i rename the Property "coolprop" the output should also have the new name

Depending on exactly what you want to do, you might be able to use CallerArgumentExpressionAttribute . That does mean you need to be willing to actually evaluate the property as well, even if you don't use it.

Note that this requires a C# 10 compiler.

Here's a complete example:

using System.Runtime.CompilerServices;

public class MyCoolProp
{
    public string FullName { get; set; }
}

class Program
{
    static MyCoolProp CoolProp { get; set; }

    static void Main()
    {
        CoolProp = new MyCoolProp { FullName = "Test" };
        WriteTextAndExpression(CoolProp.FullName);
    }

    static void WriteTextAndExpression(string text,
        [CallerArgumentExpression("text")] string expression = null)
    {
        Console.WriteLine($"{expression} = {text}");
    }
}

Output: CoolProp.FullName = Test

Source: get name of a variable or parameter (modified a bit adjusted with your case)

You can use what System.Linq.Expression provides code example:

using System.Linq.Expression
class Program
{
    public static MyCoolProp coolProp { get; set; }
    static void Main(string[] args)
    {
        coolProp = new MyCoolProp() { FullName = "John" };
        DoSomething();
    }

    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.ToString();
    }

    public static void DoSomething()
    {
        string prop = GetMemberName(() => coolProp.FullName);
        Console.WriteLine(prop);
    }

}

public class MyCoolProp
{
    public string FullName { get; set; }
}

the GetMemberName method will return the namespace, class name, object name, and variable name (depends where the method is being called)

Output: Program.coolProp.FullName

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