.Net CLR 如何实现“接口”?内部?
只是好奇 .NET CLR 如何在内部处理接口?
Q1] 当 CLR 遇到类似以下内容时会发生什么:
简单界面(下同。)
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
public void SampleMethod()
{
// Method implementation.
}
static void Main()
{
//Declare an interface instance.
ISampleInterface mySampleIntobj = new ImplementationClass(); // (A)
// Call the member.
mySampleIntobj.SampleMethod();
// Declare an interface instance.
ImplementationClass myClassObj = new ImplementationClass(); // (B)
//Call the member.
myClassObj.SampleMethod();
}
}
Q2:在上面的例子中(A)和(B)如何区分?
Q3:通用接口是否受到不同对待?
(在问这些基本问题时感觉自己像个菜鸟……无论如何……)
谢谢大家。
Just curious about how .NET CLR handles interfaces internally?
Q1] What happens when CLR encounters something like :
simple interface example. (same used below.)
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
public void SampleMethod()
{
// Method implementation.
}
static void Main()
{
//Declare an interface instance.
ISampleInterface mySampleIntobj = new ImplementationClass(); // (A)
// Call the member.
mySampleIntobj.SampleMethod();
// Declare an interface instance.
ImplementationClass myClassObj = new ImplementationClass(); // (B)
//Call the member.
myClassObj.SampleMethod();
}
}
Q2 : In the above example how are (A) and (B) differentiated ?
Q3 : Are Generic Interfaces treated differently?
(Feel like a noob when asking basic questions like these ...anyways....)
Thx all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些代码实际上没有区别。两者最终都会调用相同的函数。通过类类型调用方法可能会带来较小的性能优势。
如果您想了解如何实现这些内容,请查看虚拟方法表。
有关更深入的信息,请参阅此。
There are practically no differences in those bits of code. Both end up calling the same function. There may be minor performance benefits in calling the method through the class type.
If you want to how these stuff are implemented, have a look at Virtual Method Tables.
For deeper information, see this.
与直接使用类类型实例化相比,在创建对象引用时使用接口被认为是更好的做法。这属于接口编程原则。
这意味着您可以使用依赖注入之类的东西甚至可能是反射来更改在运行时实现相同接口的具体类。与对具体类型进行编程相比,如果您对接口进行编程,则不需要更改您的代码。
Using the interface while creating the object reference is considered a better practice as compared to directly instanciating it with a class type. This comes under the programming to an interface principle.
This means you can change the concrete class which implements the same interface at runtime using something like dependency injection or even may be reflection. Your code will not be required to be changed if you program to an interface as compared to programming to an concrete type.