C#for Action<>中的typedef的等价物和/或Func<>

时间:2015-06-24 11:24:32

标签: c# types delegates

谷歌搜索后看起来并不乐观,但我想知道在C#中使用Action<T>Func<in T, out TResult>时是否存在某种混叠或类型定义方式?

我已经看过Equivalent of typedef in c#,它表示在一个编译范围内,您可以在某些情况下使用using构造,但这似乎不适用于Action' s和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

2 个答案:

答案 0 :(得分:6)

经过一些搜索后,好像delegate来救援(见Creating delegates manually vs using Action/Func delegatesA: Custom delegate types vs Func and 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);

答案 1 :(得分:4)

using System;

namespace Example
{
    using MyAction = Action<int>;

    internal class Program
    {
    }

   private void DoSomething(MyAction action)
   {
   }
}
相关问题