简体   繁体   中英

Implementing an interface

I'm confused about the implementation of interfaces.

According to MSDN ICollection<T> has the property IsReadOnly

-And-

According to MSDN Collection<T> implements ICollection<T>

-So-

I thought that Collection<T> would have the property IsReadOnly .

-However-

Collection<string> testCollection = new Collection<string>();
Console.WriteLine(testCollection.IsReadOnly);

The above code gives the compiler error:

'System.Collections.ObjectModel.Collection<string>' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type

'System.Collections.ObjectModel.Collection<string>' could be found (are you missing a using directive or an assembly reference?)

-While-

Collection<string> testInterface = new Collection<string>();
Console.WriteLine(((ICollection<string>)testInterface).IsReadOnly);

The above code works.

-Question-

I thought classes implementing interfaces had to implement every property, so why doesn't testCollection have the IsReadOnly property unless you cast it as ICollection<string> ?

It is probably implementing the property explicitly .

C# enables you to define methods as "explicitly implemented interface methods/properties" which are only visible if you have a reference of the exact interface. This enables you to provide a "cleaner" API, without so much noise.

Interfaces can be implemented in couple of ways. Explicitly and implicitly.

Explicit Implementation: When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface

Implicit Implementation: These can be accessed the interface methods and properties as if they were part of the class.

IsReadonly property is implemented explicitly therefore it is not accessible via class directly. Take a look here .

Example:

public interface ITest
{
    void SomeMethod();
    void SomeMethod2();
}

public ITest : ITest
{

    void ITest.SomeMethod() {} //explicit implentation
    public void SomeMethod2(){} //implicity implementation
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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