简体   繁体   English

C#性能问题:typeof(MyClass)与this.GetType()

[英]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 . log4net配置手册的第一个示例中,作者使用typeof(MyApp)来获取包含类MyApp的类型。 Is there a reason not to use this.GetType() , performance-wise? 有没有理由不使用this.GetType() ,性能方面? Because it seems to me that this.GetType() is much safer from potential copy-paste errors when copying into another class. 因为在我看来,当复制到另一个类时,这个this.GetType()比潜在的复制粘贴错误更安全。

typeof(Foo) is a static type lookup; typeof(Foo)是一种静态类型查找; essentially it occurs at compile time, so you only get the explicitly named type. 本质上它发生在编译时,所以你只得到明确命名的类型。

GetType() is a dynamic type lookup; GetType()是动态类型查找; 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) . 所以它在理论上“慢”,但是它给你的东西是你无法从typeof(T) If you need one or the other for your design, the speed isn't going to be a factor. 如果您的设计需要一个或另一个,速度不会成为一个因素。

Performance issues aside, in the provided example, GetType isn't even an option because it is an instance method; 除了性能问题之外,在提供的示例中, GetType甚至不是一个选项,因为它是一个实例方法; it can't be called from a field-initializer. 它不能从字段初始化程序中调用。 In any case, since the intent is to initialize a static field from a static 'context', logically a this reference can't be available - so going down the static-constructor route wouldn't help with allowing GetType either. 在任何情况下,由于意图是从静态“上下文”初始化静态字段,逻辑上this引用不可用 - 因此沿着静态构造函数路由下去也无助于允许GetType

// Can't use GetType() - the this reference is not available.
private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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