允许属性构造函数取决于AttributeUsage

时间:2019-02-07 09:55:19

标签: c# reflection attributes

我有一个可以应用于类或属性的属性。 此类确实有两个构造函数。一个接受类型,一个接受类型和一个字符串。

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

我可以像

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

我想将其限制为这种用法。像这样使用它才有意义。

以下用法现在被认为是有效的,但它们不应如此。

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

可以做到吗?

我可以为其创建两个单独的类。一个DcProxyForClass和一个DcProxyForProperty。并像

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

但是这种方式使代码的可读性降低,因为从语义上讲,它们也是如此。

1 个答案:

答案 0 :(得分:0)

不,您基本上不能这样做。

选项:

  1. 忍受它,如果使用了错误的重载,则会在运行时引发异常
  2. 具有两个单独的属性,每个属性一个(如您已经建议的那样)-大概使用一个通用的基本类型属性
  3. 与之一起生活,但是编写一个代码分析器(Roslyn等)来检测场景并在IDE / build中对其进行标记(大概与“ 1”结合使用)