CLS兼容的属性和数组参数 [英] CLS compliant attributes and array parameters

查看:194
本文介绍了CLS兼容的属性和数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了接受它的构造函数(PARAMS)阵列的属性。

I have created an attribute that accepts a (params) array in its constructor.

internal class MyTestAttribute : Attribute
{
    public MyTestAttribute (params Options[] options)
    {
        ....
    }
}

选项这里是一个枚举(有很多值),所以示例调用网站将

Option here is an enum (with lots of values), so a sample call site will be

[MyTest(Option.One, Option.Three)]
internal void SomeMethod(int param1, long param2)
{
  ....
}

一切是桃色为止,设置工作,但我收到一个阵列的属性参数是不符合CLS 的在每次调用现场报警。现在,我不得不承认,我并不需要使用这个组件从任何其他的C#,我也不做警告-AS-错误,但数百警告越来越烦。

Everything is peachy so far, and the setup works, but I'm receiving an "Arrays as attribute arguments is not CLS-compliant" warning on each call-site. Now, I have to admit that I do not need to use this assembly from anywhere other that C#, nor do I do warnings-as-errors, but the hundreds of warnings are getting annoying.

显而易见的解决方案是关闭CLS遵守,但此刻我不能这样做。

The obvious solution is to turn off CLS-compliance, but at the moment I can't do that.

有一些其他的方法来创建的属性,将仍然做同样的事情,但摆脱了警告?

Is there some other approach to the creation of the attribute that will still do the same thing, but get rid of the warnings?

推荐答案

有两种选择:

1:你可以添加一些重载来代替:

1: you could add some overloads instead:

private MyTestAttribute(Option[] options) {...}
public MyTestAttribute(Option option0)
          : this(new[] {option0}) {}
public MyTestAttribute(Option option0, Option option1)
          : this(new[] {option0, option1}) {}
public MyTestAttribute(Option option0, Option option1, Option option2)
          : this(new[] {option0, option1, option2}) {}
// add a few more, without going crazy

2:如果选项是一个枚举,标志着枚举为 [国旗] 枚举,并有来电者将它们结合起来:

2: if Options is an enum, mark the enum as a [Flags] enum, and have the caller combine them:

[MyTest(Option.One | Option.Two)]

[Flags]
public enum Option {
     None = 0,
     One = 1,
     Two = 2,
     Three = 4,
     Four = 8,
     ...
}

这篇关于CLS兼容的属性和数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆