我正在使用 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;}
如您所见,错误消息是属性名称加上“是必需的”字符串。我需要的不是键入属性名称和每个属性的消息,而是使用通用方法 composer,它将返回装饰属性的名称和我添加的字符串,例如:
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;
}
这只是一个关于如何在属性上捕获自定义属性的演示。您必须弄清楚如何管理它们的列表,或者您需要什么来生成您需要的返回类型。也许将它映射到也被引用的“pi.Name”?我不知道你到底需要什么。
关于c# - 从属性中获取属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734871/