FxCop: Returning Matrix as Property (C#)

家住魔仙堡 提交于 2019-12-12 04:13:00

问题


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.


回答1:


I suggest, you create a class Matrix<T> that accepts a T[][] into its constructor and can be converted to T[][] and make your properties in Defaults return a Matrix<double> instance. The conversion can either be implemented implicitly, explicitly or using a method.




回答2:


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:

Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.

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?



来源:https://stackoverflow.com/questions/6596166/fxcop-returning-matrix-as-property-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!