何时使用属性和方法?属性、方法

2023-09-03 12:14:41 作者:用生命在耍帅

我是新来的.NET世界中有来自C ++和我想要更好地了解性能。我注意到,在.NET框架微软使用性能得到处都是。是否有使用属性,而不是创建get / set方法的优势在哪里?是否有一个通用准则(以及命名约定)何时应该使用属性?

I'm new to the .NET world having come from C++ and I'm trying to better understand properties. I noticed in the .NET framework Microsoft uses properties all over the place. Is there an advantage for using properties rather than creating get/set methods? Is there a general guideline (as well as naming convention) for when one should use properties?

推荐答案

这是纯粹的语法糖。在后端,它被编译成普通get和set方法。

It is pure syntactic sugar. On the back end, it is compiled into plain get and set methods.

使用,因为公约的它,它看起来更好。

Use it because of convention, and that it looks nicer.

一些准则是当它有抛出异常或去错了,请不要使用属性,但明确的getter / setter方法​​的高风险。但一般即使这样,他们的使用。

Some guidelines are that when it has a high risk of throwing Exceptions or going wrong, don't use properties but explicit getters/setters. But generally even then they are used.