没有私有变量的C#自定义获取/设置器 [英] C# Custom getter/setter without private variable

查看:197
本文介绍了没有私有变量的C#自定义获取/设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习了c#,所以当我学习编写属性时,被教导要这样做:

I learned c# recently, so when I learned to write properties, I was taught to do it like this:

public string Name { get; set; }

汽车性能很棒!但是现在我正在尝试做一些更复杂的事情,因此我需要编写一对自定义的访问器.

Auto properties are great! But now I'm trying to do something a little more complicated, so I need to write a custom pair of accessors.

private string _Name;
public string Name {
    get { return _Name; }
    set { _Name = value }
}

我知道编译器在使用auto时会在一个模糊的深度内生成一个私有实例变量,但是我很喜欢,不想让那个私有变量看上去毫无意义.

I know the compiler makes a private instance variable down in it's murky depths when one uses autos, but I'm spoiled and don't want that private variable sitting around looking pointless.

是否可以使用没有私有变量的自定义访问器?

Is there a way to use custom accessors without a private variable?

推荐答案

属性根本不需要后备变量(字段).尽管它们可以用于封装简单字段,但是您也可以使用它们来访问其他数据.

Properties don't need backing variables (fields) at all. While they can be used for encapsulating simple fields you can also use them to access other data.

public Decimal GrandTotal { get { return FreightTotal + TaxTotal + LineTotal; } }

public string SomeStatus { get { return SomeMethodCall(); } }

如果目标是简单地用属性封装某些字段,那么如果您不使用自动属性,则需要某种支持字段.

If the goal is to simply encapsulate some field with a property you would need some sort of backing field if you are not using automatic properties.

这篇关于没有私有变量的C#自定义获取/设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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