C#接口。隐式实现与明确的实施接口、明确、隐式

2023-09-02 01:16:29 作者:眸里有星辰

什么是实现接口的差异隐式和明确在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.