你经常看到C#速记getter / setter方法的滥用? [英] How often do you see abuse of C# shorthand getters/setters?

查看:200
本文介绍了你经常看到C#速记getter / setter方法的滥用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,您可以创建的getter /比其他语言更简单的方法制定者:

In C# you can create getter/setters in a simpler way than other languages:

public int FooBar { get; set; }

这将创建一个内部的私有变量,你不能直接解决,与外部财产FooBar的'直接访问它。

This creates an internal private variable which you can't address directly, with the external property 'FooBar' to access it directly.

我的问题是 - 你经常看到这种滥用?这似乎是它具有较高的潜力,往往破坏封装最佳实践。不要误会我的意思,我在你的代码库使用它作为合适的,只读只写类型的属性呢局部变化,但你有什么不愉快的经历与从其他作者?

My question is - how often do you see this abused? It seems like it has a high potential to violate encapsulation best-practices often. Don't get me wrong, I use it as appropriate, and partial variations of it for read-only write-only types of properties, but what are your unpleasant experiences with it from other authors in your code base?

澄清:滥用的预期定义的确可以创造,当私有变量是合适的这样的属性

Clarification: the intended definition of abuse would indeed be creating such a property when private variables are appropriate.

推荐答案

我已经看到了滥用(在我看来)。特别是,当开发人员的正常的写:

I've seen it abused (in my opinion). In particular, when the developer would normally write:

private readonly int foo;
public int Foo
{ 
    get 
    { 
        return foo;
    }
}



他们有时会写:

they'll sometimes write:

public int Foo { get; private set; }



是的,它短。是的,从类的外部它具有相同的外观 - 但我不认为这是同样的事情,因为后者形式允许的财产,以在同级别其他地方进行设置。这也意味着,如果该属性未在构造函数中设置,并且该字段不是只读的CLR,有没有警告。这些细微的差别,但只是去为第二个形式,因为它更简单,而忽略了不同的感觉就像滥用对我来说,即使是轻微的。

Yes, it's shorter. Yes, from outside the class it has the same appearance - but I don't view these as the same thing, as the latter form allows the property to be set elsewhere in the same class. It also means that there's no warning if the property isn't set in the constructor, and the field isn't readonly for the CLR. These are subtle differences, but just going for the second form because it's simpler and ignoring the differences feels like abuse to me, even if it's minor.

幸运的是,这是现在可作为C#6:

Fortunately, this is now available as of C# 6:

// Foo can only be set in the constructor, which corresponds to a direct field set
public int Foo { get; }

这篇关于你经常看到C#速记getter / setter方法的滥用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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