Custom attribute in C #: how to create an attribute that defines several other attributes?

I have the following attributes defined in my Name field:

[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(MyResources))]
[Display(Order = 0, Name = ResXStrings.UserName, ResourceType = typeof(MyResources))]
public string Name { get; set; }

I want to create a custom attribute that looks like this:

[MyAttribute(DisplayName = "Username", ErrorMessage = "ValidationErrorRequiredField", ResourceType = typeof(MyResources))]
public string Name { get; set; }

which defines two other attributes in the code (required and displayed).

How to implement this?

UPDATE This is not possible. Thanks to everyone who helped answer my question.

+3
source share
4 answers

I do not think you can. Because attribute consumers often find them by type, your new attribute should be both RequiredAttribute and DisplayAttribute. C # does not support multiple inheritance, so there is no way to make such a class.

+2

, . , - , , , .. .

, , , .

- (, System.Web.Mvc.ActionFilterAttribute), , , .

, , , , .

+2
+1

This is not possible directly , but you can do it with some settings in the design of your application, but I would not recommend doing it because if you do, you violate SRP for a long time by putting two different responsibilities in one class.

Remember that a class should always have one reason to change.

0
source

Source: https://habr.com/ru/post/1757118/


All Articles