C# 从属性中获取属性的名称

C# 从属性中获取属性的名称,c#,asp.net,asp.net-mvc,asp.net-mvc-4,web,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Web,我正在使用C#4.5和ASP.NETMVC5。 我有以下资料: [Required(ErrorMessage = "Prop1 is required")] public string Prop1 { get;set;} [Required(ErrorMessage = "Prop2 is required")] public string Prop2 { get;set;} 如您所见,错误消息是属性名称加上“is required”字符串。我需要的不是为每个属性键入属性名和消息,而是使用通

我正在使用C#4.5和ASP.NETMVC5。 我有以下资料:

[Required(ErrorMessage = "Prop1 is required")]
public string Prop1 { get;set;}

[Required(ErrorMessage = "Prop2 is required")]
public string Prop2 { get;set;}
如您所见,错误消息是属性名称加上“is required”字符串。我需要的不是为每个属性键入属性名和消息,而是使用通用方法生成器,它将返回装饰属性的名称和我添加的字符串,类似于:

public string GetMessage()
{
    // Caller property should be a variable that is retrieved dynamically 
    // that holds the name of the property that called the function
    return CallerProperty + " is required";
}
因此,现在我可以使用户:

[Required(ErrorMessage = GetMessage())]
public string Prop2 { get;set;}
简而言之:如何知道由属性修饰的属性名。

使用反射

public List<Required> CallerProperty<T>(T source)
{
    List<Required> result = new List<Required>();
    Type targetInfo = target.GetType();
    var propertiesToLoop = source.GetProperties();
    foreach (PropertyInfo pi in propertiesToLoop)
    {
        Required possible = pi.GetCustomAttribute<Required>();
        if(possible != null)
        {
            result.Add(possible);
            string name = pi.Name; //This is the property name of the property that has a required attribute
        }
    }
    return result;
}
公共列表调用方属性(T源)
{
列表结果=新列表();
类型targetInfo=target.GetType();
var propertiesToLoop=source.GetProperties();
foreach(PropertyInfo pi在propertiesToLoop中)
{
必需的可能值=pi.GetCustomAttribute();
如果(可能!=null)
{
结果。添加(可能);
string name=pi.name;//这是具有必需属性的属性的属性名称
}
}
返回结果;
}
这只是一个演示如何捕获属性上的自定义属性。为了生成所需的返回类型,您必须确定如何管理它们的列表,或者您需要的任何东西。也许将其映射为“pi.Name”也被引用?我不知道你到底需要什么

您可以使用“nameof”表达式,如下所示:

class Class1
{
    [CustomAttr("prop Name: " + nameof(MyProperty))]
    public int MyProperty { get; set; }
}

public class CustomAttr : Attribute
{
    public CustomAttr(string test)
    {

    }
}

这是不可能的-属性是元数据,必须在编译时知道。但是您只需要
ErrorMessage=“{0}是必需的”
这就是我想要的,谢谢