简体   繁体   中英

A constrained generic delegate in C#

I would like to have a delegate that is constrained to returning one of two types; an ActionResult or a string . Is this possible?

No, it's not possible (at least not in C# 4 and below). There's no support for "or" constraints on generic type parameters.

There's also no constraint that restricts a type argument to be an exact type. All constraints restrict the base types of the type argument. They cannot restrict you from inheriting from them.

No, it's not. Besides, what would be the benefit of doing this? Unless the two types have something in common, then there's nothing that you can really do with the return type.

Consider some code that calls the delegate:

var returnValue = someDelegate();

What type is var in this case? The only common ancestor of string and ActionResult is object , so that's all you can get from it. From a static typing point of view, you may as well just declare the return type as object .

As other answers have explained, you cannot do this, however you could work around it by passing different continutations for each return type:

public delegate void MultiPathDelegate(Action<ActionResult> arAction, Action<string> strAction);

So checking the return type occurs in the delegate instead of the caller.

Like Zakalwe, I also don't see any point in doing this, but..

You could define two overloaded methods which accept a Func<string> and a Func<ActionResult> respectively. A private method could take Delegate and do further things with it.

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