如何声明带有输出参数的通用委托

发布于 2024-08-25 08:48:34 字数 215 浏览 12 评论 0原文

Func,只是不编译,如何声明我希望第二个参数是out 1?

我想这样使用它:

 public class Foo()
 {
     public Func<a, out b, bool> DetectMethod;
 }

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;
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆悲凉 2024-09-01 08:48:34

实际上,Func 只是 .NET Framework 中声明的一个简单委托。实际上,那里声明了几个 Func 委托:

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)

所以你唯一能做的就是声明你的自定义委托:

delegate bool MyFunc<T1, T2>(T1 a, out T2 b)

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)
瑾夏年华 2024-09-01 08:48:34

您需要创建自己的委托类型,如下所示:

delegate bool MyFunc(Type1 a, out Type2 b);

You need to make your own delegate type, like this:

delegate bool MyFunc(Type1 a, out Type2 b);
蓝天 2024-09-01 08:48:34

您可能想重新考虑您的设计。您真的需要通过添加输出参数来使代码复杂化吗?

您可以将 bool 返回类型和第二个输出类型包装在它们自己的类(或 .NET 4.0 Tuple)中,并将其用作返回类型:

public Func<Type1, Tuple<Type2, bool>> DetectMethod;

当然,当您想使用委托来引用 try-parse 方法时,您可以这样做正确的轨道,您需要定义一个新的委托,正如其他人已经描述的那样。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文