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

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

问题描述

当我们定义一个属性时

    public string Name {get; set;}

dot net 可以制作我们的属性代码.但是当我们使用

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.

使用

  • just get : 意味着您只能检索值.您永远无法设置属性值(即使在包含类中)
  • just set : 表示您只能设置值.您无法检索属性值.

对于普通属性

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