C# - 是否可以使用新接口扩展现有的内置类
我刚刚学习 C#,现在遇到一个问题。 :-) 在 C++ 中,我喜欢使用“const 引用”作为参数来避免这种情况 被调用的方法改变了我传递的对象。
我在某处读到我可以做某事。与 C# 中的接口类似。 在界面中,我只是放置一些“getter”以允许该方法进行只读访问 到我的对象。
现在猜测,我想向我的 C# 方法传递一个内置容器,如“List”。 但我想避免该方法更改该列表中的某些内容。 只是只读!
我的第一个想法是: - 我创建一个名为 IMyOwnInterface 的新接口,它也使用接口 IList
我的新接口 IMyOwnInterface 仅包含“getters”
我将我的方法更改为 sth 。就像 MyLittleMethod(IMyOwnInterface if)
现在方法“MyLittleMethod”只能看到“getters”,这是我放入自己的界面中的,而不是 IList 的“setters”
这可能吗? 有人可以给我提示吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想使用List.AsReadOnly。
http://msdn.microsoft.com/en-us /library/e78dcd75(VS.80).aspx
You want to use List.AsReadOnly.
http://msdn.microsoft.com/en-us/library/e78dcd75(VS.80).aspx
是的,我相信这会起作用。试一试,让我们知道它是如何工作的:D
Yes, I believe that would work. Give it a shot, and let us know how it works :D
答案是否定的:
IList 没有实现 IMyOwnInterface,因此您无法转换它。
在这种情况下,您可以使用 ReadOnlycollection:
The answer is no:
IList does not implement IMyOwnInterface so you can't cast it.
In this case you can use ReadOnlycollection:
对于接口,基本上只能通过继承或一些代理的东西(或者通过 RealProxy 实现显式地使用适配器类,或者使用库来执行类似的操作,例如 LinFu)。
但是,您可以开箱即用地使用委托对具有匹配签名的单个方法进行后期绑定。
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.