Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

.net - C# performance question: typeof(MyClass) vs. this.GetType()

In the first example of the log4net configuration manual the author uses typeof(MyApp) to get the type of the containing class MyApp. Is there a reason not to use this.GetType(), performance-wise? Because it seems to me that this.GetType() is much safer from potential copy-paste errors when copying into another class.

question from:https://stackoverflow.com/questions/5451035/c-sharp-performance-question-typeofmyclass-vs-this-gettype

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

typeof(Foo) is a static type lookup; essentially it occurs at compile time, so you only get the explicitly named type.

GetType() is a dynamic type lookup; it's a virtual method that gets called at runtime and will give you the exact type even if you are using polymorphism. So it's "slower", theoretically, but it's giving you something you can't get from typeof(T). If you need one or the other for your design, the speed isn't going to be a factor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...