Class 中 属性 的 c# 全名

c# Full Name of Property in Class

我有一个class

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

在另一个 Class 中,我将其设为 属性:

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

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

实际结果是:“全名”

但我想要这样的组合:“coolprop.FullName”

我不想做这样的事情:

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

也许可以在扩展中使用?

如果我将 属性 重命名为“coolprop”,输出也应该具有新名称

具体取决于您想做什么,您可能能够使用CallerArgumentExpressionAttribute。这确实意味着您也需要愿意实际评估 属性,即使您不使用它也是如此。

请注意,这需要 C# 10 编译器。

这是一个完整的例子:

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

输出:CoolProp.FullName = Test

来源: get name of a variable or parameter(根据您的情况稍作调整)

您可以使用 System.Linq.Expression 提供的内容 代码示例:

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; }
}

GetMemberName方法将return命名空间、class名称、对象名称和变量名称(取决于调用方法的位置)

输出:Program.coolProp.FullName