我为什么要使用一个字段的自动实现的属性呢? [英] Why should I use an automatically implemented property instead of a field?

查看:114
本文介绍了我为什么要使用一个字段的自动实现的属性呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两者之间:

使用属性:

class WithProperty
{
    public string MyString {get; set;}
}

使用领域:

class WithField
{
    public string MyString;
}

显然,我应该挑头之一。为什么呢?

Apparently I'm supposed to pick the first one. Why?

我听到的说法,这里的要点是允许界面的改变,但 如果我有第二个,并将其更改为第一位的,没有其他的code必须 曾经有改变。当重新编译一切都只是将指向 属性。

I've heard the argument that the point here is to allow interface changes, but if I have the second one, and change it to the first one, no other code should ever have to change. When recompiled everything's just going to point to the property instead.

我失去了一些东西在这里很重要?

Am I missing something important here?

推荐答案

最重要的区别是,如果你使用了一块地,后来需要将其更改为一个属性(比如,执行一些验证)然后调用您的code所有库将需要重新编译。这是真的,你可以编译完全相同的code。如果名称保持不变 - 但你的code中的消费者仍需要重新编译。这是因为生成来获取值的IL的一个字段和属性之间的不同。如果它已经是一个属性,你可以做出改变,而不强迫你的code来改变消费者的青睐。

The most important difference is the fact, that if you use a field, and later need to change it to a property (say, to enforce some validation), then all libraries calling your code will need to be recompiled. It's true that you can compile the exact same code if the name stays the same - but the consumers of your code will still need to be recompiled. This is because the IL generated to get the value is different between a field and a property. If it already is a property, you can make a change without forcing consumers of your code to change.

这可能会或可能不会是一个问题。但是属性几乎是code相同的量,被认为是最好的做法。我总是会去的属性。

This may or may not be an issue for you. But the property is almost the same amount of code, and is considered best practice. I would always go for the property.

这篇关于我为什么要使用一个字段的自动实现的属性呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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