简体   繁体   English

可以obj.GetType()。IsInterface是真的吗?

[英]Can obj.GetType().IsInterface be true?

While doing something almost completely irrelevant, a question popped into my head: 在做一些几乎完全无关紧要的事情时,一个问题突然出现在我脑海中:

Can an expression of the form obj.GetType().IsInterface ever be true in a codebase consisting exclusively of C# code? obj.GetType().IsInterface形式的表达式是否可以在仅由C#代码组成的代码库中成立?

I suspect the answer is no, because: 我怀疑答案是否定的,因为:

  • GetType() will always return the runtime type. GetType()将始终返回运行时类型。
  • The runtime type for concrete types matches the invoked constructor. 具体类型的运行时类型与调用的构造函数匹配。 Thus, it is never an interface, because interfaces don't have constructors. 因此,它永远不是一个接口,因为接口没有构造函数。
  • Anonymous types cannot implement an interface (and if they did, they'd still have their anonymous class type). 匿名类型无法实现接口(如果他们这样做,他们仍然有他们的匿名类类型)。
  • Instances of internal classes of other assemblies implementing public interfaces will still have the class as the runtime type. 实现公共接口的其他程序集的内部类的实例仍将该类作为运行时类型。
  • Using [ComImport, CoClass(typeof(MyClass))] on an interface makes it look like you can instantiate it, but the constructor call actually instantiates the referenced class. 在接口上使用[ComImport, CoClass(typeof(MyClass))]使它看起来像你可以实例化它,但构造函数调用实际上实例化了引用的类。

I can't think of any other case. 我想不出任何其他情况。 Am I missing something, or is my guess correct? 我错过了什么,或者我猜对了吗?

Can an expression of the form obj.GetType().IsInterface ever be true in a codebase consisting exclusively of C# code? obj.GetType().IsInterface形式的表达式是否可以在仅由C#代码组成的代码库中成立?

Yes - but probably not the way you were thinking of: 是的 - 但可能不是你想的那样:

using System;

public class EvilClass
{
    public new Type GetType()
    {
        return typeof(IDisposable);
    }
}

class Test
{
    static void Main()
    {
        EvilClass obj = new EvilClass();
        Console.WriteLine(obj.GetType().IsInterface); // True
    }
}

Slightly similarly, I believe you could create a subclass of RealProxy which would intercept the call and return an interface type. 稍微类似的,我相信你可以创建一个RealProxy的子类,它将拦截调用并返回一个接口类型。

If you mean "will the return value of the GetType() method declared in object ever be an interface type" - in that case I suspect the answer is no. 如果你的意思是“将在object声明的GetType()方法的返回值将是一个接口类型” - 在这种情况下,我怀疑答案是否定的。

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

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