自动实现的属性C# [英] Auto-Implemented Properties c#

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

问题描述


  1. 可能有人解释我背后有什么用自动实现的属性C#的想法?

     公共类客户
    {
        公众诠释ID {搞定;组; }
        公共字符串名称{;组; }
    }

    我可以使用私有字段属性的动机,所以我们可以决定一个人如何访问私有字段。但在这里 - 它就像定义字段从首位公开。不是吗?


  2. 有定义字段设置为公共常量或定义它有一个只能获得属性之间的差异?



解决方案

一个公共的自动属性是不一样的公共领域,它们不是二进制兼容的。如果您实现一个公共领域,后来想添加一些逻辑,你必须把它变成一个属性,从而引进了重大更改(因为二进制不兼容的)。这就是为什么许多公约指出,你永远不应该公开的公共领域,而是使用属性的原因。

因此​​,自动属性只是任何简单的非私有类值成员一个方便的起点,允许一个后来添加逻辑,同时保持二进制兼容性。

  1. could someone explain me what's the idea behind using Auto-Implemented Properties c#?

    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

    I get the motivation to use properties for private field, so we can determine how one can access a private field. But here - it's just like defining the field to be public from the first place. no?

  2. Is there a difference between defining a field to be "public const" or define it to have a get-only property ?

解决方案

A public automatic property is not the same as a public field, they are not binary compatible. If you implement a public field and later on want to add some logic, you will have to change it into a property and thereby introduce a breaking change (because of the binary incompatibility). This is the reason why many conventions state that you should never expose public fields but rather use properties.

So, automatic properties are just a convenient starting point for any simple non-private class value member, allowing one to add logic later on while keeping binary compatibility.

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

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