【问题标题】:Custom attributes not behaving like data annotations自定义属性的行为不像数据注释
【发布时间】:2019-12-01 19:10:35
【问题描述】:

我正在尝试在控制台应用程序中创建自定义属性,但它不起作用。我的自定义属性永远不会被调用。我在这里找到了一个很好的例子Custom Attribute not being hit 但对其实施不满意。

我想知道数据注释在 MVC 中是如何工作的。我们不必单独调用它。

MVC 是否在后台调用那些数据注释属性?

我希望创建可以在任何类属性上使用的自定义属性,例如数据注释属性。但是像上面的链接那样单独调用它并不是我想要的。

这是我尝试过的:

using System;

namespace AttributePractice
{
    [AttributeUsage(AttributeTargets.Property)]
    public class CustomMessageAttribute : Attribute
    {
        public static readonly CustomMessageAttribute Default = new CustomMessageAttribute();

        protected string Message { get; set; }

        public CustomMessageAttribute() : this(string.Empty)
        {
            Console.WriteLine("Default message is empty");
        }

        public CustomMessageAttribute(string message)
        {
            Message = message;
        }

        public string MyMessage =>
            Message;

        public override bool Equals(object obj)
        {
            if (obj == this)
                return true;
            if (obj is CustomMessageAttribute customMessageAttribute)
                return customMessageAttribute.Message == MyMessage;
            return false;
        }

        public override int GetHashCode()
        {
            return MyMessage.GetHashCode();
        }

        public override bool IsDefaultAttribute()
        {
            return Equals(Default);
        }
    }

    public class Person
    {
        //This never works
        // I am looking to use this attribute anywhere without calling it 
        //   separately , same like data annotations
        [CustomMessage("Hello world")] 
        public string Name { get; set; }

        public int Age { get; set; }

        public void DisplayPerson()
        {
            Console.WriteLine(Name);
            Console.WriteLine(Age);
        }
    }

    internal static class Program
    {
        private static void Main(string[] args)
        {
            var personObj = new Person
            {
                Name = "Tom",
                Age = 28
            };

            personObj.DisplayPerson();
        }
    }
}

谁能告诉我如何让我的自定义属性像数据注释一样工作?

【问题讨论】:

  • 属性本身不做任何事情。一些代码必须寻找属性并对它们做一些事情。这就是数据注释所发生的事情。
  • “MVC 是否在后台调用这些数据注释属性” - 是的。它在渲染或验证模型时使用反射来检查模型的属性。
  • 谢谢!但是我怎样才能为我的控制台应用程序进行类似的反射或任何替代类。任何代码提示。
  • 您不能使用“不单独调用它”的属性。您必须编写反射代码才能使用该属性。我建议从Attribute 上的文档开始

标签: c# asp.net-mvc data-annotations custom-attributes


【解决方案1】:

是的,如果您需要 10 个自定义属性,您应该单独创建 10 个。

【讨论】:

  • 也许完成你的答案?
  • @NetMage 是的,感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多