c#中get前缀背后的原因

Reason behind the get prefix in c#

考虑到在 c# 中我们对带有 getters 和 setter 的属性有特定的语法,为什么有些属性是通过方法(通常以 'Get' 为前缀)而不是 getter?

例如为什么:

var properties = object
    .GetType()
    .GetProperties();

而不是使用 getter,例如:

var properties = object
    .Type
    .Properties

GetProperties() 答案很简单:它 returns 一个新的属性数组(过滤后的(仅 public)内部属性数组的副本),并且来自 MSDN:

Do use a method, rather than a property, in the following situations.

The operation returns a copy of an internal state (this does not include copies of value type objects returned on the stack).

The operation returns an array.

对于GetType()我不知道。

Design Guidelines for Developing Class Libraries 有话要说:

Consider using a property if the member represents a logical attribute of the type.

GetType() 是在 object 上定义的,所有类型的基类型。您不希望 each 类型始终具有 Type 属性.

Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

据我所知,需要进行一些转换才能将 CLR 的内部元数据转换为 PropertyInfo 对象。