Unity(Unity5)中C#中的属性-是否可以避免使用后备变量 [英] Properties in c# in Unity (Unity5) - can you avoid the backing variable

查看:103
本文介绍了Unity(Unity5)中C#中的属性-是否可以避免使用后备变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Unity5(很难确切知道正在使用的是哪个版本的c#/Mono/.Net),我们所做的属性完全像这样:

With Unity5 (it's hard to know exactly what version of c#/Mono/.Net is being used), we do properties exactly like this:

private int _distance;
public int Distance
    {
    private set
        {
        _distance = value;
        controls.Blahblah(_distance);
        }
    get
        {
        Debug.Log("hah!);
        return _distance;
        }
    }

但是请考虑一下c#中的新自动属性" ,看起来像是

But consider the new "automatic properties" in c#, which seem to be like

 public int Distance {get; set;}   // ?

但是我不知道如何在getter/setter中做某事"?

but I don't know how to "do something" in the getter/setter ??

换句话说,当手动"制作属性时,是否有一种方法可以自动生成后备变量(以及便捷性-使其私有)?

Or in other words, is there a way to auto generate the backing variable (as well as the convenience -- to keep it private) when "manually" making a Property?

要重复操作,因为这被标记为重复,我如何在吸气剂/装填剂过程中自动执行Property惯用语...

To repeat since this was marked as a duplicate, how can I "do stuff" in the automatic Property idiom during the getter/setter ...

...或者相反...

... or conversely ...

如果您编写自己的手动"属性,如何隐藏,摆脱或自动提供支持者?

how to hide, get rid of, or automatically supply the backer if you write your own "manual" properties?

请注意,您或其他程序员当然可以不小心碰到_underscore后备变量:有什么办法可以避免这种情况?

Note that of course you or another programmer can accidentally touch the _underscore backing variable: is there any way at all to avoid that??

推荐答案

如果要在getter/setter中执行某些操作",则只能使用分配给字段的方式,而不能使用自动属性.对于示例代码所描述的用例,不能选择自动属性.拥有明确的支持字段并没有错.

You can't use auto-properties if you want to "do something" in the getter/setter, apart from just assigning to the field. For the use-case described by your example code, auto-properties are not an option. There is nothing wrong with having an explicit backing field.

这篇关于Unity(Unity5)中C#中的属性-是否可以避免使用后备变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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