隐式实现与明确的实施

隐式实现与明确的实施

本文介绍了C#接口。隐式实现与明确的实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是实现接口的差异隐式明确在C#?

What are the differences in implementing interfaces implicitly and explicitly in C#?

当你应该使用隐式的,当你应该使用明确的?

When should you use implicit and when should you use explicit?

有什么优点和/或缺点,一方或另一方?

Are there any pros and/or cons to one or the other?

微软官方指南(从第一版框架设计准则)规定,使用明确的实现不是推荐使用,因为它提供了code异常行为。

Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.

我觉得这个指引是非常有效的pre-IOC-时间,当你不通过周围的事物的接口。

I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.

能否在这方面任何人碰呢?

Could anyone touch on that aspect as well?

推荐答案

是,当你通过在你的类成员定义接口。 明确是,当你的类接口中定义的方法。我知道这听起​​来很混乱,但这里是我的意思是: IList.CopyTo 将被隐式实现为:

Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:

public void CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

和明确的:

void ICollection.CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

所不同的是,你暗中创建是通过你的类访问时,它被转换为该类以及当其投作为接口。显式实现允许它仅被访问时转换为接口本身

The difference being that implicitly is accessible through your class you created when it is cast as that class as well as when its cast as the interface. Explicit implementation allows it to only be accessible when cast as the interface itself.

MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.

我用明确的主要是为了保证实施清洁,或当​​我需要两个实现。但不管我很少使用它。

I use explicit primarily to keep the implementation clean, or when I need two implementations. But regardless I rarely use it.

我相信有更多的理由来使用它/不使用它,其他人就会发布。

I am sure there are more reasons to use it/not use it that others will post.

next交 在这个线程的背后都有极好的理由。

See the next post in this thread for excellent reasoning behind each.

这篇关于C#接口。隐式实现与明确的实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:37