C#3.0自动属性-是否有用? [英] C# 3.0 auto-properties — useful or not?

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

问题描述

注意:这是在我开始C#时发布的。凭借2014年的知识,我可以真正地说出自动属性是C#语言有史以来最好的事情之一。

我习惯于创建自己的

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; }

我知道这更是一个哲学/主观的问题,但是有没有理由使用这些自动-属性,而不是为每个字段保存五行代码?我个人的抱怨是这些属性对我隐藏了东西,我也不是黑魔法的忠实拥护者。

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.

我看到了节省大量代码的好处。 (一对六行),而不会在以后失去更改getter / setter逻辑的能力,但是话又说回来,我已经可以通过简单地声明一个公共字段 Public string Title而无需使用{get;组; }块,从而节省更多代码。

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?

推荐答案

我们一直在Stack Overflow中使用它们。

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天全站免登陆