简体   繁体   中英

Generic Delegate Storage and Usage

delegate IEnumerable<T> GetFromSQLDelegate<T>(...);
public GetFromSQLDelegate myFunctionToCall;

The above does not compile because myFunctionToCall does not specify a type. I'm trying to "store" a generic delegate such that I can invoke it later as a regular generic function:

// ... somewhere in another code base ...
return MyObject.myFunctionToCall<string>(...);

C# complains because I'm not specifying a concrete type on the delegate storage property. Is there a (good) way to "store" a delegate capable of invoking a generic function without implementing various concrete type delegate scenarios?

You can store the value as System.Delegate , make it private , and define a function GetDelegate<T> that casts your stored delegate to the appropriate type:

private Delegate storedDelegate;

public myFunctionToCall<T> GetDelegate<T>() {
    return (myFunctionToCall<T>)storedDelegate;
}

You can then call it like this:

return MyObject.GetDelegate<string>()(...);

There is a little bit of ugliness going on around the ()(...) syntax, but it should probably do the trick.

There are no pieces to your puzzle in C#:

  • you can't have non-generic variable of generic type with non-specified type
  • you can't create function that matches such imaginary signature
  • you can't call function and specify type.

So answer is NO. There are multiple different ways to achieve similar behaviors, so if you specify what your actual goal is someone will come up with an approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM