简体   繁体   中英

C# - Is it possible to extend an existing built-in class with a new Interface

I am just learning C# and I have a problem now. :-) In C++ I loved to use "const reference" as a parameter to avoid that the called method changes my passed object.

I read somewhere that I can do sth. similar in C# by using Interfaces. In the interface I would just put some "getters" to allow the method a readonly access to my object.

Now guess, that I want to pass my C# method a built-in container like "List". But I want to avoid that the method changes something in that list. Just read only!

My first thought was: - I create a new Interface called IMyOwnInterface, which uses the interface IList as well

  • My new interface IMyOwnInterface contains only "getters"

  • I change my method to sth. like that MyLittleMethod(IMyOwnInterface if)

  • Now the method "MyLittleMethod" can just see the "getters", which I put in my own interface and not the "setters" of IList

Is this possible? Can someone give me a hint?

Yes, I believe that would work. Give it a shot, and let us know how it works :D

The answer is no:

IList does not implement IMyOwnInterface so you can't cast it.

IList list = ...
MyLittleMethod((IMyOwnInterface)list)    // Compiler errror here

In this case you can use ReadOnlycollection:

IList list = ...
MyLittleMethod(new ReadOnlyCollection(list))

With interfaces, it's basically only possible through inheritance or with some proxy stuff (either explicit with an adapter class, via a RealProxy implementation, or with a library to do things like that, such as LinFu).

However, out of the box you can use delegates to do late-binding for single methods with matching signature.

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