[英]c# Full Name of Property in Class
I have a class我有一个 class
public class MyCoolProp
{
public string FullName {get;set;}
}
and in another Class i have this as Property:在另一个 Class 中,我将其作为属性:
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"但我想要这样的组合:“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如果我将属性重命名为“coolprop”,output 也应该具有新名称
Depending on exactly what you want to do, you might be able to use CallerArgumentExpressionAttribute
.具体取决于您想要做什么,您可以使用
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.请注意,这需要一个 C# 10 编译器。
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
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:您可以使用 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; }
}
the GetMemberName
method will return the namespace, class name, object name, and variable name (depends where the method is being called) GetMemberName
方法将返回命名空间、class 名称、object 名称和变量名称(取决于调用方法的位置)
Output: Program.coolProp.FullName
Output:
Program.coolProp.FullName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.