首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从属性中获取属性的名称

从属性中获取属性的名称
EN

Stack Overflow用户
提问于 2018-06-07 15:03:58
回答 2查看 438关注 0票数 3

我使用的是C# 4.5和ASP.NET MVC5。我有以下内容:

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

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

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50734871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档