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

标签 c# .net arrays properties

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

但是,在一些情况下,我可以看到这种观点似乎有点极端。

案例一

属性在数据容器上,其余数据是属性。该属性不太可能被重构为每个请求生成一个新数组。

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)字段正在重构为属性(至少提供封装的幻觉)。

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

    // Other members...
}

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

Background: I am porting a library that others will consume from Java into C# and trying to come up with some kind of rule of thumb when to use properties and when not to (since in Java they are either methods or fields). Unfortunately, the widespread use of public array fields in the application makes the decision difficult - do I really need to make methods GetBar() and SetBar(int[] bar) if I know for certain it should always act like an array variable? Or in this case should these public fields remain as public fields in .NET rather than making properties? (yuck)

最佳答案

首先,您提到的指南是针对设计类库的——如果您的代码将被其他开发人员使用,那么它们比在您维护的应用程序中使用时要重要得多。

数组的问题在于调用者可以修改其中的元素 - 我不认为仅仅因为这些准则就将数组公开为公共(public)字段很有意义(没有冒犯),因为它不能解决该问题。

在可能的情况下,您可以将它们公开为 IReadOnlyList<T> :

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

如果应用程序确实要求调用者可以更改数组的内容,您应该绝对避免使用方法,因为那样会使它更加模糊:

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;更直观。

关于c# - 创建数组属性是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718781/

相关文章:

c# - 将虚拟文件拖放到 FileDrop 接收目标

c# - 如何将参数传递给 TeamCity Test Runner?

c# - 如何禁用 EF 代码优先中链接表的级联删除?

javascript - 对数组使用 for ...of 可以吗?

c++ - 如何获取动态创建内存的数组大小

javascript - 在javascript中获取数组中所有按钮的id

c# - 从 AJAX 发布的字符串中删除 BOM 字符

检测到 C# 无法访问的代码

c# - 链接文本框 C# SQL Server

c# - Procdump -e 在非致命异常上创建转储