C#3.0自动属性 ​​- 有用或没有? [英] C# 3.0 auto-properties - useful or not?

查看:134
本文介绍了C#3.0自动属性 ​​- 有用或没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注:这是当我开始了C#中发布。随着2014年的知识,我可以真正地说,自动性能之间都发生在C#语言的最好的事情。

我习惯于使用私人和公共领域在C#中创建我的属性:

I am used to create my properties in C# using a private and a public field:

private string title;
public string Title
{
    get { return title;  }
    set { title = value;  }
}

现在,随着 .NET 的3.0,我们得到了自动属性:

Now, with .NET 3.0, we got auto-properties:

public string Title { get; set; }

我知道这是更多的是哲学/主观题,但没有任何理由,除了从节约五行code为每个字段使用这些自动特性?我个人的抱怨是,这些属性是从我隐藏的东西,我不是黑魔法的忠实粉丝。

I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.

其实,隐藏的私有字段甚至没有出现在调试器,这是正常鉴于该get / set函数什么也不做。但是,当我想真正实现一些的getter / setter的逻辑,我无论如何也要使用公/对。

In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.

我看到,我节省了大量的code(一个VS六条线),而不会丢失后改变的getter / setter逻辑能力的好处,但话又说回来,我已经可以做到这一点通过简单地声明一个公共领域公共字符串名称,而不需要的{获得;组; }块,因此,即使节省更多code。

I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.

那么,我在这里丢失?为什么会有人真的想使用自动属性?

So, what am I missing here? Why would anyone actually want to use auto-properties?

推荐答案

我们使用他们所有的时间在堆栈溢出。

We use them all the time in Stack Overflow.

您可能也有兴趣属性与公共变量的讨论。恕我直言,这真的是这是一种反应,并为此目的,它的伟大。

You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.

这篇关于C#3.0自动属性 ​​- 有用或没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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