C# 结构是否应该只有只读属性 [英] Should a C# struct have only read-only properties

查看:27
本文介绍了C# 结构是否应该只有只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 StackOverflow 上不纯方法的问题此处 这让我想到了结构设计的最佳实践.

I was reading though a question about impure methods on StackOverflow here and it got me thinking about struct design best practise.

阅读有关创建不可变结构的示例 此处 属性定义为仅使用 getter.

Reading an example about creating an immutable struct here properties are defined as with getters only.

public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public bool HasValue { get { return hasValue; } }

其他地方的其他示例,包括在 System.Drawing.Point 中的属性有 getter 和 setter.

Other examples elsewhere including in System.Drawing.Point the properties have getters and setters.

public int Y {
    get {
        return y;
    }
    set {
        y = value;
    }
}

设计指南没有具体说明,但它们非常简洁.结构属性的推荐方法是什么?只读还是允许写入?

The design guidelines don't specify but they are quite terse. What would be the recommended approach for struct properties? Readonly or allow writing?

推荐答案

设计指南非常清楚:

X 不要定义可变值类型.

可变值类型有几个问题.例如,当属性 getter 返回值类型时,调用者会收到一个副本.因为副本是隐式创建的,开发人员可能不会意识到他们正在改变副本,而不是原始值.此外,某些语言(尤其是动态语言)在使用可变值类型时存在问题,因为即使是局部变量,在取消引用时也会导致复制.

Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

至于 System.Drawing.Point,还有其他重要的因素(如性能)足以打破此设计准则.请参阅 为什么是 System.Drawing矩形、点、大小等可变结构而不是类?

As for System.Drawing.Point, there are other factors (like performance) that were important enough to break this design guideline. See Why are System.Drawing Rectangle, Point, Size etc mutable structs and not classes?

这篇关于C# 结构是否应该只有只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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