jeudi 7 février 2019

Allow Attribute constructor dependent on AttributeUsage

I am having an attribute that can be applied either on a class or on a property. This class does have two constructors. One accepting a type, one accepting a type and a string.

 [AttributeUsage(
        AttributeTargets.Property | 
        AttributeTargets.Class, 
        AllowMultiple = true)]    
class DcProxyAttribute : Attribute{
     public DcProxyAttribute(Type type){ /*...*/ }
     public DcProxyAttribute(Type type, string str){ /*...*/ }
}

I can use it like

   [DcProxy(typeof(SomeType)]
   class MyClass {
       [DcProxy(typeof(SomeType, "Hello World")] 
       public string SomeProperty { get; set;}
   }

I want to restrict it to this usage. It make only sense to use it like that.

The following usages are now considered valid, but they should not.

   [DcProxy(typeof(SomeType, "Hello world")]
   class MyClass {
       [DcProxy(typeof(SomeType)] 
       public string SomeProperty { get; set;}
   }

Can this be done?

I could create two separate classes for it. A DcProxyForClass and A DcProxyForProperty. And use it like

  [DcProxyForClass(typeof(SomeType)]
  class MyClass {
       [DcProxyForProperty(typeof(SomeType, "Hello World")] 
       public string SomeProperty { get; set;}
  }

but this kind of make the code less readable, since semantically speaking they do the same.





Aucun commentaire:

Enregistrer un commentaire