Callbacks in C#

后端 未结 5 1437
孤独总比滥情好
孤独总比滥情好 2020-12-28 17:52

I want to have a library that will have a function in it that accepts an object for it\'s parameter.

With this object I want to be able to call a specified function

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 18:27

    Sounds like a perfect recipe for delegates - in particular, callbacks with delegates are exactly how this is handled in the asynchronous pattern in .NET.

    The caller would usually pass you some state and a delegate, and you store both of them in whatever context you've got, then call the delegate passing it the state and whatever result you might have.

    You could either make the state just object or potentially use a generic delegate and take state of the appropriate type, e.g.

    public delegate void Callback(T state, OperationResult result)
    

    Then:

    public void DoSomeOperation(int otherParameterForWhateverReason,
                                Callback callback, T state)
    

    As you're using .NET 3.5 you might want to use the existing Func<...> and Action<...> delegate types, but you may find it makes it clearer to declare your own. (The name may make it clearer what you're using it for.)

提交回复
热议问题