C# 相机代码中的奇怪行
Strange line in C# camera code
我的团队正在为一个机器人项目编写文档。我们目前正在记录一些相机代码,但我们不理解某些行。
public Mat Image { get; set; }
public double GyroAngle { get; set; }
谁能解释一下这些行是做什么的?如果 GyroAngle
只是一个 double
为什么它有 { get; set; }
?提前致谢。
一点也不奇怪。
- 字段不能在接口中使用,但属性可以。
- 大多数 .NET 绑定都可以针对 属性 完成。不是字段
- 您可以更改 属性 的实现并保留契约,这样就不会破坏相关代码。例如,在 setter 中您可以添加验证。你今天可能没有验证,但如果你将来有,你可以添加它。如果它是一个字段,并且您将其更改为 属性,则会发生许多不好的事情,例如二进制序列化可能会中断。
如果您将字段公开为 public,一些工具也会对您大喊大叫。
MSDN 有一些有用的信息。
public string FirstName { get; set; } = "Jane";
The class that is shown in the previous example is mutable. Client code can change the values in objects after they are created. In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties.
我的团队正在为一个机器人项目编写文档。我们目前正在记录一些相机代码,但我们不理解某些行。
public Mat Image { get; set; }
public double GyroAngle { get; set; }
谁能解释一下这些行是做什么的?如果 GyroAngle
只是一个 double
为什么它有 { get; set; }
?提前致谢。
一点也不奇怪。
- 字段不能在接口中使用,但属性可以。
- 大多数 .NET 绑定都可以针对 属性 完成。不是字段
- 您可以更改 属性 的实现并保留契约,这样就不会破坏相关代码。例如,在 setter 中您可以添加验证。你今天可能没有验证,但如果你将来有,你可以添加它。如果它是一个字段,并且您将其更改为 属性,则会发生许多不好的事情,例如二进制序列化可能会中断。
如果您将字段公开为 public,一些工具也会对您大喊大叫。
MSDN 有一些有用的信息。
public string FirstName { get; set; } = "Jane";
The class that is shown in the previous example is mutable. Client code can change the values in objects after they are created. In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties.