hol*_*roy 7 c# delegates types
谷歌搜索后看起来并不乐观,但我想知道在使用Action<T>或Func<in T, out TResult>在C#中是否有某种混叠或类型定义的方法?
我已经在c#中看到了typedef的等价,它说在一个编译范围内你可以在using某些情况下使用该构造,但就我所知,这似乎并不适用于Action's和Funcs.
我想要这样做的原因是我想要一个动作用作多个函数的参数,如果我在某个时间点决定改变动作,那么很多地方都要改变它们作为参数类型和作为变量类型.
?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;
}
Run Code Online (Sandbox Code Playgroud)
是否有一些构造要使用,它可以定义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);
Run Code Online (Sandbox Code Playgroud)
using System;
namespace Example
{
using MyAction = Action<int>;
internal class Program
{
}
private void DoSomething(MyAction action)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3144 次 |
| 最近记录: |