gpt4 book ai didi

c# - 在不允许调用委托(delegate)的函数中将委托(delegate)作为参数传递

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:56 24 4
gpt4 key购买 nike

我想让这个函数在我的程序中工作,但 Visual Studio 告诉我 MyFunc 是一个变量,但使用起来像一个方法,但这正是我想要做的。试图调用它。

static private void TryThisFunc(Delegate MyFunc)
{
try
{
MyFunc(); // MyFunc is a variable but is used like a method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

最佳答案

您尚未指定要使用的委托(delegate)的类型。它可以是一个接受参数的委托(delegate)——在这种情况下,显然你不能不带参数地调用它。您可能希望使用特定委托(delegate)类型,例如

static private void TryThisFunc(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

关于c# - 在不允许调用委托(delegate)的函数中将委托(delegate)作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com