从属性中获取属性的名称

时间:2018-06-07 07:03:58

标签: c# asp.net asp.net-mvc asp.net-mvc-4 web

我正在使用C#4.5和ASP.NET MVC 5。 我有以下内容:

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

简而言之:我如何知道属性修饰的属性名称。

2 个答案:

答案 0 :(得分:0)

使用反射。

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

这只是一个如何在属性上捕获自定义属性的演示。您必须弄清楚如何管理它们的列表,或者您需要的任何内容,以便生成所需的返回类型。也许用&#34; pi.Name&#34;来映射它。还引用?我不确切地知道你需要什么。

答案 1 :(得分:0)

您可以使用&#34; nameof&#34;表达如下:

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

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

    }
}