简体   繁体   中英

Why is Object.GetType() a method instead of a property?

From a design perspective, I wonder why the .NET creators chose System.Object.GetType() instead of a System.Object.Type read-only property.

Is it just a (very minor) design flaw or is there rationale behind there? Any lights welcome.

If you look at the GetType() declaration in Reflector you'll find this:

[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType(); 

What that combination of attribute and extern means is that this method is actually implemented in unmanaged code inside the .NET runtime itself. The GUID question in this article goes into further details. They obviously did this for performance reasons after determining that figuring out the Type would be faster if handled at a lower level.

This leads to two reasons not to implement the GetType method as a property. Firstly you can't define properties extern as you can with methods, so it would need to be handled in native .NET code. Secondly even if you could define them as extern, performing an unsafe, unmanaged call from inside a property would definitely break the guidelines for property usage since it's much harder to guarantee that there are no side effects.

The guidelines say that a property should represent a state of the object, it should not be expensive performance wise, and it should not have side effects apart from computing/setting that state. My guess is GetType() does not respect these rules so they made it a method.

GetType() is a slightly expensive operation. If it were a property it would encourage uses like

DoStuff(obj.Type);
....
DoStuff(obj.Type);

etc.

instead of

Type type = obj.GetType();
DoStuff(type);
....
DoStuff(type); 

and that would be not so optimal. So they made it a method to suggest that it should be called sparingly.

据我所知,对于内部字段或值而言,通常认为这是很好的做法,这些字段或值很容易计算为使用属性公开,而其他值可能需要更多时间或其他资源来计算,使用方法公开。

Only Microsoft can answer that question, but I think it's because several classes in the .NET Framework create their own overloaded versions of GetType() with extra parameters. If it would have been a property, they couldn't use the same name (because properties don't have parameters).

Just my thoughts on the subject.

A bit late reply but crashed into the question while trying to find something related.

It is possible for GetType to throw an exception. Framework guidelines state that properties should not throw exceptions. This is one more reason why it should be a method instead of property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM