[英]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()
将始终返回运行时类型。 [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.