简体   繁体   English

是否可以声明没有参数的泛型委托?

[英]Is it possible to declare generic delegate with no parameters?

I have... 我有...

Func<string> del2 = new Func<string>(MyMethod);

and I really want to do.. 我真的很想..

Func<> del2 = new Func<>(MyMethod);

so the return type of the callback method is void. 所以回调方法的返回类型是void。 Is this possible using the generic type func? 这可能使用泛型类型func吗?

The Func family of delegates is for methods that take zero or more parameters and return a value. Func系列的代表用于获取零个或多个参数并返回值的方法。 For methods that take zero or more parameters an don't return a value use one of the Action delegates. 对于采用零个或多个参数的方法,不使用其中一个Action委托返回值。 If the method has no parameters, use the non-generic version of Action : 如果方法没有参数,请使用Action的非泛型版本

Action del = MyMethod;

Yes a function returning void (no value) is a Action 是的,返回void(无值)的函数是一个Action

public Test()
{
    // first approach
    Action firstApproach = delegate
    {
        // do your stuff
    };
    firstApproach();

    //second approach 
    Action secondApproach = MyMethod;
    secondApproach();
}

void MyMethod()
{
    // do your stuff
}

hope this helps 希望这可以帮助

使用操作委托类型

In cases where you're 'forced' to use Func<T> , eg in an internal generic API which you want to reuse, you can just define it as new Func<object>(() => { SomeStuff(); return null; }); 如果您“被迫”使用Func<T> ,例如在您想要重用的内部通用API中,您可以将其定义为new Func<object>(() => { SomeStuff(); return null; }); .

Here is a code example using Lambda expressions instead of Action/Func delegates. 下面是使用Lambda表达式而不是Action / Func委托的代码示例。

delegate void TestDelegate();

static void Main(string[] args)
{
  TestDelegate testDelegate = () => { /*your code*/; };

  testDelegate();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM