C# 在C中创建表示多个子属性的属性#

C# 在C中创建表示多个子属性的属性#,c#,C#,我在我的一个项目中有以下类型的代码示例 [Obfuscation(Exclude = true)] [UsedImplicitly] public DelegateCommand<object> OpenXCommand { get; private set; } [模糊处理(排除=真)] [正确使用] public DelegateCommand OpenXCommand{get;private set;} 我发现属性在代码中添加了很多“噪音”——我也认

我在我的一个项目中有以下类型的代码示例

    [Obfuscation(Exclude = true)]
    [UsedImplicitly]
    public DelegateCommand<object> OpenXCommand { get; private set; }
[模糊处理(排除=真)]
[正确使用]
public DelegateCommand OpenXCommand{get;private set;}
我发现属性在代码中添加了很多“噪音”——我也认为它在某种程度上违反了DRY原则,因为我可能在一个类中有几个类似的属性,所有这些属性都具有相同的属性装饰

Q:有什么方法可以设置一个表示子属性组合的属性吗?

理想情况下,我想要这样的东西

    [MyStandardCommandAttribute]
    public DelegateCommand<object> OpenXCommand { get; private set; }
[MyStandardCommandAttribute]
public DelegateCommand OpenXCommand{get;private set;}

我以前没有实现过自己的属性,所以我不确定这是否可行。有什么建议吗?

没有。您的一个属性不能“是”
模糊处理
同时使用
(C#中没有多重继承)


查找例如usedimplicityattribute的代码无法知道MyStandardCommandAttribute应该表示usedimplicityattribute(除非您使用所有这些属性控制所有代码)。

不幸的是,在C中无法做到这一点

但是,如果您控制读取这些属性的位置(使用反射),则可以按照约定执行

例如,您可以有一个标记接口,该接口将使用它代理的属性“注释”您的属性(听起来像元属性):

在反射代码上使用此扩展方法:

public static object[] GetCustomAttributesWithProxied(this MemberInfo self, bool inherit) {
  var attributes = self.GetCustomAttributes(inherit);
  return attributes.SelectMany(ExpandProxies).ToArray();
}

private static object[] ExpandProxies(object attribute) {
  if (attribute is IAttributeProxy) {
    return ((IAttributeProxy)attribute).GetProxiedAttributes().
      SelectMany(ExpandProxies).ToArray(); // don't create an endless loop with proxies!
  }
  else {
    return new object[] { attribute };
  }
}

您使用什么来反映属性上的属性?顺便说一句,您可以将这两个属性组合到一行:
[模糊处理(排除=true),正确使用]
@svick-thaks-我没有意识到这一点感谢您的建议
public interface IAttributeProxy {
  Attribute[] GetProxiedAttributes();
}

public class MyStandardCommandAttribute : Attribute, IAttributeProxy {
  public Attribute[] GetProxiedAttributes() {
    return new Attribute[] {
      new ObfuscationAttribute { Exclude = true },
      new UsedImplicitlyAttribute()
    };
  }
}
public static object[] GetCustomAttributesWithProxied(this MemberInfo self, bool inherit) {
  var attributes = self.GetCustomAttributes(inherit);
  return attributes.SelectMany(ExpandProxies).ToArray();
}

private static object[] ExpandProxies(object attribute) {
  if (attribute is IAttributeProxy) {
    return ((IAttributeProxy)attribute).GetProxiedAttributes().
      SelectMany(ExpandProxies).ToArray(); // don't create an endless loop with proxies!
  }
  else {
    return new object[] { attribute };
  }
}