Iasyncresult - 为什么它不仅仅是对象,为什么它是接口?
我只是不明白为什么 IAsyncResult 是一个接口而不是简单的对象。我没记错的话,接口只包含方法名称而没有实现,所以我看不到它在这里是如何使用的,因为我没有派生它的任何类,也没有重写它的方法?我只是很困惑..谢谢
I just cannot figure out what why IAsyncResult is an interface instead of simple object. As I remember correctly, interface contains only method names without implementation so I canot see how it is used here as I do not derive any class of it nor override its methods? I am just confused..Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果它只是一个对象,它可以是任何东西 - 并且您可以不依赖于存在的某些属性和/或方法,就像当您知道您将获得一个实现该接口的对象时一样
IAsyncResult
。由于您要返回的对象必须实现相关接口,因此您可以依赖以下属性:
AsyncState
、AsyncWaitHandle
、CompletedSynchronously
和IsCompleted
将出现。如果你只有一个对象并且返回一个
int
- 你将如何获得你需要的那些属性?If it were just an object, it could be anything - and you could not rely on certain properties and/or methods being present, like you can when you know you'll get an object that implements the interface
IAsyncResult
.Since the object you're getting back must be implementing the interface in question, you can rely on the fact that the properties
AsyncState
,AsyncWaitHandle
,CompletedSynchronously
andIsCompleted
will be present.If you had just an object and you got back an
int
- how would you get those properties you need??这样,结果可以是任何类型的对象,它实现了 IAsyncResult 接口。
你是对的,接口只包含方法/属性,没有实现。
在这种情况下,保证 AsyncResult 对象包含“异步框架”所需的方法。
IAsyncResult 包含四个属性:
使用异步方法时只需要这些属性。如果它是一个对象,我认为你的灵活性就会降低。
Like this, the result can be any type of object, which implements the IAsyncResult interface.
You're right that an interface only contains methods/properties without implementation.
In this case, it is garanteed that the AsyncResult object contains the methods which are needed by the 'Async-framework'.
The IAsyncResult contains four properties:
Those properties are simply required when working with Async methods. If it would be an object, you would be less flexible I think.
因为“ASyncResult”本身并不具体。
由于 C# 只允许单一继承,因此通过将其设为接口,您可以在您选择的任何对象类型上实现它。
例如,如果我的方法返回类型 Foo,我可以通过创建一个子类并简单地转换它来为我的应用程序创建一个异步返回类型,
而不是编写代码来提取值。
Because an "ASyncResult" in itself is nothing concrete.
Because C# only allows single inheretance, by making it an interface you can implement it on any object type you choose.
For example, if I my method returns type Foo, I can create an async return type for my app simply by creating a subclass saying
And simply cast it as opposed writing code to extract values.