【问题标题】:Get the name of the property from attribute从属性中获取属性的名称
【发布时间】:2018-11-16 23:50:50
【问题描述】:

我正在使用 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;}

如您所见,错误消息是属性名称加上“是必需的”字符串。我需要的不是为每个属性键入属性名称和消息,而是使用通用方法作曲家,它将返回修饰属性的名称和我添加的字符串,例如:

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

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

【问题讨论】:

  • 这是不可能的 - 属性是元数据,必须在编译磁贴处知道。但你只需要ErrorMessage = "{0} is required"
  • 这就是我想要的,谢谢

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


【解决方案1】:

使用反射。

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”来映射它?我不确切知道你需要什么。

【讨论】:

    【解决方案2】:

    您可以按如下方式使用“nameof”表达式:

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

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      相关资源
      最近更新 更多