与c#中的typedef等价,用于Action<>;和/或Func<>;
本文关键字:gt lt Func Action 中的 typedef 等价 用于 | 更新日期: 2023-09-27 17:59:17
在谷歌上搜索后,它看起来不太有前景,但我想知道在C#中使用Action<T>
或Func<in T, out TResult>
时是否有某种别名或类型定义方法?
我已经在c#中看到了typedef的等价物,它说在一个编译范围内,在某些情况下可以使用using
构造,但据我所知,这似乎不适用于Action
和Func
。
我想这样做的原因是,我希望一个操作被用作多个函数的参数,如果我在某个时间点决定更改该操作,那么有很多地方可以同时更改为参数类型和变量类型。
?typedef? MyAction Action<int, int>;
public static SomeFunc(WindowClass window, int number, MyAction callbackAction) {
...
SomeOtherFunc(callbackAction);
...
}
// In another file/class/...
private MyAction theCallback;
public static SomeOtherFunc(MyAction callbackAction) {
theCallback = callbackAction;
}
是否有一些可以定义代码段中所示MyAction
的构造可供使用?
经过更多的搜索,似乎delegate
已经成功了(请参阅手动创建代理与使用Action/Func代理和A:自定义委托类型与Func和Action)。请说明为什么这不是一个解决方案或可能存在的陷阱。
有了代表,我可以重写第一行给定的代码示例:
public delegate void MyAction(int aNumber, int anotherNumber);
// Keep the rest of the code example
// To call one can still use anonymous actions/func/...
SomeFunc(myWindow, 109, (int a, int b) => Console.Writeline);
using System;
namespace Example
{
using MyAction = Action<int>;
internal class Program
{
}
private void DoSomething(MyAction action)
{
}
}