我将举一个.NET的例子.
ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
Run Code Online (Sandbox Code Playgroud)
在这里您可以看到ConcurrentDictionary实现字典接口.但是我无法Add<TKey,TValue>从ConcurrentDictionary实例访问方法.这怎么可能?
IDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
dictionary.Add(3, 3); //no errors
ConcurrentDictionary<int, int> concurrentDictionary = new ConcurrentDictionary<int, int>();
concurrentDictionary.Add(3, 3); //Cannot access private method here
Run Code Online (Sandbox Code Playgroud)
更新:
我知道如何访问它,但我不知道显式实现接口可以允许将访问修饰符更改为内部.它仍然不允许将其设为私有.它是否正确?关于该部分的更详细解释将是有帮助的.另外,我想知道一些有效的用例.
FtpWebResponse实现了IDisposable,但它没有Dispose方法.怎么可能?
(非常新手的问题)
我可能误解了这一点,但在MSDN上我相信它说在你编写的每个类中实现Dispose析构函数是一个好习惯.我应该(你)真的为我写的每个类实现IDisposable接口吗?
另外,实现一个接口的正确语法是在"类"声明之后将"Implements"关键字放在行上吗?我把它放在与"class"相同的行上,我收到了一个错误.
还有一个?:在编写接口实现的方法时,必须遵循这种语法,例如:
Public Sub Dispose() Implements IDisposable.Dispose
Run Code Online (Sandbox Code Playgroud)
我在上面的代码中感到好奇的是,如果我需要将实现的方法声明为"Implements System.IDisposable.Dispose"
我在一个项目和类中使用FileHelpersMultiRecordEngine
public sealed class MultiRecordEngine
: EventEngineBase<object>, IEnumerable, IDisposable
Run Code Online (Sandbox Code Playgroud)
这个类实现了IDisposable,但是没有公共的Dispose方法......
MultiRecordEngine eng = null;
eng.Dispose(); // <---- Results in compilation error
Run Code Online (Sandbox Code Playgroud)
在GitHub上检查这个类代码我可以看到这里明确实现的方法,第913行:
void IDisposable.Dispose()
{
Close();
GC.SuppressFinalize(this);
}
Run Code Online (Sandbox Code Playgroud)
那么...... 为什么我不能调用这个方法呢?这是有意的,如果是这样,这是一个好的做法,在什么情况下?
System.Net.HttpListenerResponse今天我一直在玩,我注意到我的知识中仍然存在明显差距using.
using (HttpListenerResponse response = context.Response)
{
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
是完全有效的代码,但是,该对象没有Dispose()方法.
为什么using还能运作?