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

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

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

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

代码语言:javascript
复制
[Required(ErrorMessage = "Prop1 is required")]
public string Prop1 { get;set;}

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

正如您所看到的,错误消息是属性名称加上“is required”字符串。我需要的不是为每个属性键入属性名称和消息,而是使用泛型方法编写器,它将返回装饰属性的名称和我添加的字符串,如下所示:

代码语言:javascript
复制
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";
}

所以现在我可以使用:

代码语言:javascript
复制
[Required(ErrorMessage = GetMessage())]
public string Prop2 { get;set;}

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

EN

回答 2

Stack Overflow用户

发布于 2018-06-07 18:11:21

使用反射。

代码语言:javascript
复制
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“?我不知道你到底需要什么。

票数 0
EN

Stack Overflow用户

发布于 2018-06-16 06:27:18

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

代码语言:javascript
复制
class Class1
{
    [CustomAttr("prop Name: " + nameof(MyProperty))]
    public int MyProperty { get; set; }
}

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

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

https://stackoverflow.com/questions/50734871

复制
相关文章

相似问题

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