C # attributes: one attribute for their rule?

Is it possible to assign a property attribute and use it to assign other attributes - by doing this without reflection?

The code:

public class CashierOut : BaseActivity { [Description("Flag indicates whether break to execution.")] [DefaultValue(false)] [MyCustomAttribute(ParameterGroups.Extended)] public bool CancelExecution { get; set; } [Description("Flag indicates whether allow exit before declation.")] [DefaultValue(true)] [MyCustomAttribute(ParameterGroups.Extended)] [DisplayName("Exit before declaration?")] public bool AllowExitBeforeDeclare { get; set; } } 

I would like to do something like this:

 public class CashierOut : BaseActivity { [MyResourceCustom("CashierOut.CancelExecution")] public bool CancelExecution { get; set; } [MyResourceCustom("CashierOut.AllowExitBeforeDeclare")] public bool AllowExitBeforeDeclare { get; set; } } public sealed class MyResourceCustom : Attribute { public string ResourcePath { get; private set; } public ParameterGroupAttribute(string resourcePath) { ResourcePath = resourcePath; // Get attributes attributes value from external resource using the path. } } 
+6
source share
3 answers

Attributes simply add metadata to the members to which they are defined - they do nothing.

You will need to use reflection to produce some kind of behavior depending on the values โ€‹โ€‹of the attribute.

This is how all attributes work: some of the tools are aware of some attributes (like the compiler and ConditionalAttribute ), but this is still done through reflection.

+6
source

Take a look at aspect-oriented programming. You can use tools like postsharp to change your code either at compile time or at runtime.

+2
source

You can add a member to MyResourceCustom that wraps Description, DefaultValue, and MyCustomAttribute in an immutable instance (possibly even a static global one, if it can be the same for everyone).

 public class MyResourceCustom : Attribute { public MyResourceCustomDescriptor Descriptor { get; private set; } public MyResourceCustom(MyResourceCustomDescriptor descriptor) : base() { Descriptor = descriptor; } public class MyResourceCustomDescriptor { public string Description { get; private set; } public bool DefaultValue { get; private set; } public ParameterGroups ParameterGroup { get; private set; } public MyResourceCustomDescriptor(string path) { // read from path } } public class MyAdvancedResouceCustomDescriptor : MyResourceCustomDescriptor { public string DisplayName { get; private set; } // etc... } 

When retrieving an attribute, you can get its Descriptor property and read the values.

As an alert, you should call it IsDefaultValue .

+1
source

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


All Articles