简体   繁体   English

使用C#的get set属性被认为是好习惯吗?

[英]Is using get set properties of C# considered good practice?

my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? 我的问题很简单,就是使用C#的get set属性被认为是好的,甚至比编写getter和setter方法更好? When you use these properties, don't you have to declare your class data members as public ? 使用这些属性时,是否必须将类数据成员声明为公共? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice. 我问这是因为我的教授说数据成员永远不应该被公开,因为它被认为是不好的做法。

This.... 这个....

class GetSetExample
{
    public int someInt { get; set; }
}

vs This... vs 这......

class NonGetSetExample
{
    private int someInt;
}

Edit: 编辑:

Thanks to all of you! 感谢大家! All of your answers helped me out, and I appropriately up-voted your answers. 你的所有答案都帮助了我,我适当地向你投了你的答案。

This: 这个:

class GetSetExample
{
    public int someInt { get; set; }
}

is really the same as this: 真的是这样的:

class GetSetExample
{
    private int _someInt;
    public int someInt {
        get { return _someInt; }
        set { _someInt = value; }
    }
}

The get; set; get; set; get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special. 语法只是一种方便的简写,当getter和setter不做任何特殊操作时你可以使用它。

Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it. 因此,您没有公开公共成员,您正在定义私有成员并提供get / set方法来访问它。

Yes, members should normally never be declared public in good design for several reasons. 是的,由于多种原因,成员通常不应在良好的设计中公开宣布。 Think about OOP where you inherit the class later. 想想稍后继承该类的OOP。 Kind of hard to override a field. 有点难以覆盖一个字段。 :-) Also it prevents you from keeping your internals from being accessed directly. :-)它还可以防止你直接访问内部。

The simplistic get; 简单化得到; set; 组; design was introduced in C# 2.0. 设计是在C#2.0中引入的。 It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see). 它与支持它的私有成员声明所有内容基本相同(在Reflector等工具中反编译它)。

public int someInt{get;set;} 

is directly equal to 直接等于

private int m_someInt;
public int someInt{
  get { return m_someInt; }
  set { m_someInt = value; }
} 

The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility. 关于使用简化的getter / setter的重要一点是,当你想稍后用更多的内容填充实现时,你不会破坏ABI的兼容性。

Don't worry about getter/setters slowing down your code through indirection. 不要担心getter / setter会通过间接方式降低代码的速度。 The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access. JIT有一个叫做内联的东西,使用getter / setter和直接字段访问一样高效。

Yes. 是。 Data members should be private and automatic properties allow it and give public access on right way. 数据成员应该是私有的,自动属性允许它并以正确的方式提供公共访问。

But you should be careful. 但你应该小心。 Understand the context is very important. 理解上下文非常重要。 In threaded application, update one property following an another related property can be harmful to consistency. 在线程应用程序中,更新一个属性跟随另一个相关属性可能会对一致性有害。 In that case, a setter method updating the two private data members in a proper way makes more sense. 在这种情况下,以适当方式更新两个私有数据成员的setter方法更有意义。

在您的第一个示例中,C#自动生成私有支持字段,因此从技术上讲,数据成员不会被声明为仅公共getter / setter。

because with public data member , that data member can be changed or can be read out of class and you cannot control read/write operation accessibility but with properties you can control read/write stream for example consider this statement : 因为对于公共数据成员,该数据成员可以更改或者可以从类中读取,并且您无法控制读/写操作可访问性,但是使用属性可以控制读/写流,例如考虑以下语句:

 public MyVar{private get; public set;}

means value of MyVar can be changed only inside of class and can be read out of class(read privately and read publicly) and this is not possible with just public data members 意味着MyVar值只能在类内部进行更改,并且可以从类中读取(私有读取并公开读取),这对于公共数据成员来说是不可能的

In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. 在“纯粹的”面向对象的方法中,根本不公开对象的状态是不行的,这适用于在.NET中实现的属性以及Java / EJB的get_set_ properteis。 The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. 我们的想法是,通过公开对象的状态,您将创建对象的内部数据表示的外部依赖关系。 A pure object design reduces all interactions to messages with parameters. 纯对象设计减少了与带参数的消息的所有交互。

Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. 回到现实世界:如果你试图在工作中实施如此严格的理论方法,你将被嘲笑出办公室或被殴打成纸浆。 Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data. 属性非常受欢迎,因为它们是纯对象设计和完全暴露的私有数据之间的合理折衷。

It's quite reasonable, and your professor (without context) is wrong. 这是非常合理的,你的教授(没有背景)是错误的。 But anyway, using "automatic properties", is fine, and you can do it whether they are public or private. 但无论如何,使用“自动属性”,很好,无论是公共还是私有,你都可以这样做。

Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props. 虽然根据我的经验,每当我使用一个时,我几乎不可避免地最终需要在那里写一些逻辑,因此不能使用汽车道具。

your professor was quite right. 你的教授是对的。

Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. 考虑一下为什么应该避免“getter”的简单示例:程序中可能有1000次调用getX()方法,并且每个调用都假定返回值是特定类型。 The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. 例如, getX()的返回值可以放在局部变量中,并且变量类型必须与返回值类型匹配。 If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. 如果您需要以X类型发生变化的方式更改对象的实现方式,那么您就会陷入困境。 If X used to be an int , but now has to be a long , you'll now get 1,000 compile errors. 如果X曾经是一个int ,但现在必须是一个long ,你现在会得到1,000个编译错误。 If you fix the problem incorrectly by casting the return value to int , the code will compile cleanly but won't work. 如果通过将返回值强制转换为int来错误地修复问题,则代码将干净地编译但不起作用。 (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. (返回值可能会被截断。)您必须修改围绕这1,000个调用中的每一个的代码以补偿更改。 I, at least, don't want to do that much work. 我,至少,不想做那么多工作。

Holub On Patterns Holub On Patterns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM