当你应该使用一个领域,而不是财产? [英] When should you use a field rather than a property?

查看:116
本文介绍了当你应该使用一个领域,而不是财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你使用一个字段,当一流的设计使用的属性?任何人都可以清楚地说明

Can anyone clearly articulate when you use a field and when to use a property in class design?

考虑:

public string Name;

或者

private string _Name;
public string Name
{
   get { return _Name; }
   set { _Name = value; }
}

我认识到,第二种方法是更恰当和灵活的,所以这就是我尝试使用,一般

I realize that the second method is more proper and flexible, so that's what I try to use, generally.

既然这样,为什么我看到人们用第一种方法?他们只是懒惰,或者是有它的正确选择某些特定的情况吗?难道仅仅是一个preference的事?

But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference?

推荐答案

好吧在C#3.0,你可以实际编写:

Well in C# 3.0 you can actually write:

public string Name {get; set;}

允许你有适当的和懒惰。

Which allows you to be proper and lazy.

一般来说,具有属性,你会得到正确的封装。您可以选择是允许设置一个值,或者得到它,或两者兼而有之。使用公共成员,你没有这样的选择。

Generally speaking, with properties, you get proper encapsulation. You have the choice to allow setting a value, or getting it, or both. Using a public member, you don't have that option.

这可能是一个部分preference,一个部分你的团队如何决定处理快速和肮脏的类定义,但我要说,使用属性的get /套。

It's probably one-part preference, and one-part how your team decides to handle quick and dirty class definitions, but I would say, use properties for get/sets.

要回答

当你使用一个属性,当一流的设计使用的属性?任何人都可以清楚地说明

Can anyone clearly articulate when you use an attribute and when to use a property in class design?

您应该永远不会使用公共属性。你应该总是使用属性。它是更安全,更灵活。这就是说,人们会偷懒,只是使用一个公共成员。然而,C#3.0,你可以用更简洁的语法定义属性,它应该满足你内心的懒惰。

You shouldn't ever use a public attribute. You should always use a property instead. It's safer and more flexible. That said, people will be lazy, and just use a public member. However, with C# 3.0 you can use a more terse syntax to define properties, which should satisfy your inner laziness.

只需输入,并按<标签> 来加快在添加一个属性懒惰

Simply type prop and hit <tab> to expedite the laziness in adding a property.

这篇关于当你应该使用一个领域,而不是财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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