Why doesn’t BeginInvoke return reference of type A

2019-04-24 17:55发布

When you call a delegate object’s BeginInvoke, the system creates an object of type AsyncResult, but BeginInvoke returns a reference of type IAsyncResult interface ( which points to AsyncResult instance) . Why doesn’t BeginInvoke instead return a reference of type AsyncResult?

thanx

2条回答
做个烂人
2楼-- · 2019-04-24 18:16

This is standard interface based programming.

By returning an IAsyncResult, the framework is free to change the internal implementation at a later time, without breaking code written against the framework's API. This, in essence, telling us, as developers, that we should not care what type of implementation is used, provided the interface (IAsyncResult) is met.

If, instead, the actual AsyncResult class was returned, then changing to a different class would break existing code.

Also, this allows the framework to use the same interface (IAsyncResult) in multiple places, whether or not the AsyncResult class is appropriate. I've taken advantage of this, personally, as I've made my own asynchronous functions which return IAsyncResult backed by a different class, which stored the information which was important to me. This allows my own code to work like the framework, without restricting me to the framework's implementation.

查看更多
不美不萌又怎样
3楼-- · 2019-04-24 18:30

Because it doesn't always return an AsyncResult. The delegate target may exist in another execution context, a RealProxy derived class may implement a proxy for it. Remoting would be an example. Returning an interface type makes that transparent.

查看更多
登录 后发表回答