为什么自动实现的属性必须同时定义get和set访问 [英] Why Automatically implemented properties must define both get and set accessors

查看:1991
本文介绍了为什么自动实现的属性必须同时定义get和set访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们定义像

    public string Name {get; set;}



点网可以使我们的物业代码。但是,当我们使用

dot net can make our properties code. but when we use

    public string Name {get;}
    public string Name {set;}

我们面对

'Hajloo.SomeThing.PropertyName.set' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.



其实为什么编译器不能确定的财产,并自动进行代码?有什么问题?

Actually why the compiler can't determine the property and make code automatically? What's the problem?

推荐答案

由于自动实现的属性生成的属性值自己的后备存储。你必须对内部存储的访问权限。

Because the auto-implemented properties generate their own backing store for the property values. You have no access to the internal store.

实现与属性。


  • 刚刚获得:也就是说你只能检索值。你永远不能设置属性值(甚至包含类)

  • 刚刚成立:意味着你只能设置的值。你不能检索的属性值。

对于正常的特性

private int _data;
public int Data{  get { return _data } };

下面父类可以做到在类下面别的地方(它不能自动道具)

Here the parent class can do the following somewhere else in the class ( which it can't with auto props)

_data = 100;

请注意:您可以定义一个自动道具这样的(这是我如何使用它最)

Note: You can define an auto-prop like this (which is how I use it the most).

public int Data { get; private set;}

这意味着该属性不能由类的外部客户端进行设置。然而,含类本身可以在酒店多次通过 this.Data = x设定; 类定义中

This means that the property can't be set by external clients of the class. However the containing class itself can set the property multiple times via this.Data = x; within the class definition.

这篇关于为什么自动实现的属性必须同时定义get和set访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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