我有一个静态类“默认”,它将保存默认矩阵,这些矩阵被转发到最后要求 double[][]
的接口。到目前为止,我只是将返回 double[][] 的静态属性放入此类中。
现在要使其符合我们公司的编码标准,代码必须符合 FxCop 的规则 CA1819,它不允许我像我一样从属性返回锯齿状数组。我将返回 IList
或 IEnumerable
而不是数组(正如所讨论的此处)。
我想“这很公平”,所以我实现了返回 IList>
的属性(尽管嵌套类型也不酷)。然而,正如我所说,我需要使用的接口最终要求使用 double[][] 矩阵。我不知道如何将此列表列表放入数组数组中无需显式转换回每个列表。当然,我可以,但这会产生大量的开销,特别是因为我什至不访问这些矩阵 - 我只将它们传递到接口。
(PS:我知道,这是界面的错,但目前我们无法改变这一点。)
编辑:我发现使用 ILists>
无论如何都没有帮助,因为它违反了 CA1006。为了让 FxCop 闭嘴,我采取的简单解决方案是将属性设置为内部。无论如何,更好的解决方案如下所述。或者,可以考虑使用索引属性,但这在 C# 中有点混乱。
I have a static class 'Defaults' which shall hold default matrices that are forwarded to an interface that asks for double[][]
in the end. So far I simply put static properties in this class that return double[][]
s.
Now to make this conform to our company's coding standards, the code must comply to FxCop's rule CA1819, which won't allow me to return a jagged array from a property like I did. And instead of arrays, I shall return IList
or IEnumerable
(as discussed here).
"Fair enough" I thought, so I implemented the property to return IList<IList<double>>
(although nested types are uncool too). However, as I said, the interface which I need to work with asks for double[][]
matrices in the end.. I have no idea how to get this list of lists into an array of arrays without explicitly converting back each list. Of course, I could, but that would create an insane amount of overhead, especially since I don't even access those matrices - I only pass them through to the interface.
(PS: I know, it's the Interface's fault, but at the moment we can't change that.)
Edit: I found out that using ILists<IList<double>>
donesn't help anyway, since it violates CA1006. The easy solution that I took to make FxCop shut up was to make the properties internal. Anyway, the nicer solution is stated below. Alternatively, one may consider to use an indexed property, which is a bit messy in C# though.
发布评论
评论(2)
我建议您创建一个类
Matrix
,该类将T[][]
接受到其构造函数中,并可以转换为T[][]< /code> 并使
Defaults
中的属性返回一个Matrix
实例。转换可以隐式、显式或使用方法来实现。I suggest, you create a class
Matrix<T>
that accepts aT[][]
into its constructor and can be converted toT[][]
and make your properties inDefaults
return aMatrix<double>
instance. The conversion can either be implemented implicitly, explicitly or using a method.FxCop 规则的目的是防止 API 用户感到困惑,并提醒 API 作者这是否是他们真正想要做的事情。
将数组作为属性返回可能会让 API 使用者对内部数据结构造成严重破坏,这可能不是 API 作者的意图。
从链接的规则来看:
他们推荐的返回数组的方法之一是将 Xxx 属性更改为 GetXxx() 方法。
这对你来说可能吗?
The FxCop rule is there to prevent confusion for the user of the API and to remind the API author if that's what they really want to do.
Returning an array as a property is a potential for API consumers to wreak havoc on an internal data structure, which is probably not the intent of the API author.
From the rule linked:
One of the ways they recommend for returning an array is to change an Xxx property to a GetXxx() method.
Is that possible for you?