创建数组属性是否有意义?

时间:2017-01-18 11:54:59

标签: c# .net arrays properties

According to MSDN,当返回数组时,应该使用方法而不是属性。他们进一步推论为什么会出现这种情况的具体例子。

然而,有几种情况我可以看到这看起来有点极端。

案例1

该属性位于数据容器中,其余数据属性。根据请求,不可能重构属性以生成新数组。

public class Foo
{
    private readonly int[] bar;
    private int fooish;

    public Foo(int[] bar, int fooish)
    {
        this.bar = bar;
        this.fooish = fooish;
    }

    public int[] Bar
    {
        get { return bar; }
    }

    public int Fooish
    {
        get { return fooish; }
    }
}

案例2

一个类的公共字段被重构为属性(至少提供封装的假象)。

public class Foo
{
    public int[] Bar { get; set; }
    public int Fooish { get; set; }

    // Other members...
}

我的问题是 - 如果我知道它们是由一个字段支持(并且可能永远都是),那么将它们变成方法是否有任何现实的论据?

  

背景:我正在移植一个其他人将从Java中使用到C#中的库,并尝试在使用属性时提出某种经验法则,何时不使用(因为在Java中它们是方法或领域)。不幸的是,在应用程序中广泛使用公共数组字段使得决策变得困难 - 如果我确定它应该总是像数组变量一样,我真的需要创建方法GetBar()SetBar(int[] bar)吗?或者在这种情况下,这些公共字段是否应该作为.NET中的公共字段而不是制作属性? (呸)

1 个答案:

答案 0 :(得分:4)

首先,您提到的指南是用于设计类库 - 如果您的代码将由其他开发人员使用,则它们比您在维护的应用程序中使用时更重要。

数组的问题在于调用者可以修改其中的元素 - 我不认为将数组暴露为公共字段仅仅是因为这些指南很有意义(没有冒犯),因为它没有解决这个问题。 / p>

如果可能,您可以将其公开为IReadOnlyList<T>

private int[] arr;
public IReadOnlyList<int> Arr { get { return arr; }}

如果应用程序 要求调用者可以更改数组的内容,那么肯定避免使用方法,因为这会使其更加模糊:< / p>

class MyClass
{
    private int[] arr;

    // can't clone the array, because your application requires the caller to change elements
    public int[] GetArr() { return arr; }
}

...

// very unclear for the caller that he's actually modifying the array on the obj instance
int[] values = obj.GetArr();
values[2] = 12;

在这种情况下,obj.Arr[2] = 12;更直观。

相关问题