问题
This question already has an answer here:
- Func<T> with out parameter 4 answers
Func<a, out b, bool>
, just don't compile, how to declare that i want the second parameter be an out
one?
I want to use it like this:
public class Foo()
{
public Func<a, out b, bool> DetectMethod;
}
回答1:
Actually, Func is just a simple delegate declared in the .NET Framework. Actually, there are several Func delegates declared there:
delegate TResult Func<TResult>()
delegate TResult Func<T, TResult>(T obj)
delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, T3, TResult>(T1 obj1, T2 obj2, T3 obj3)
delegate TResult Func<T1, T2, T3, T4, TResult>(T1 obj1, T2 obj2, T3 obj3, T4 obj4)
delegate TResult Func<T1, T2, ... , T16, TResult>(T1 obj1, T2 obj2, ..., T16 obj16)
So the only thing you can do is declare your custom delegate:
delegate bool MyFunc<T1, T2>(T1 a, out T2 b)
回答2:
You need to make your own delegate type, like this:
delegate bool MyFunc(Type1 a, out Type2 b);
回答3:
You might want to rethink your design. Do you really need to complicate your code by adding an out parameter?
You can wrap the bool return type and the second out type in their own class (or .NET 4.0 Tuple) and use that as a return type:
public Func<Type1, Tuple<Type2, bool>> DetectMethod;
Of course when you want to use the delegates to reference try-parse methods, you are on the right track and you'll need to define a new delegate as others already described.
来源:https://stackoverflow.com/questions/2448010/how-to-declare-a-generic-delegate-with-an-out-parameter