首页 > 解决方案 > 允许依赖于 AttributeUsage 的 Attribute 构造函数

问题描述

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

 [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;}
  }

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

标签: c#reflectionattributes

解决方案


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

选项:

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

推荐阅读