Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#代表和全球范围界定_C#_Delegates_Global - Fatal编程技术网

C#代表和全球范围界定

C#代表和全球范围界定,c#,delegates,global,C#,Delegates,Global,我是C#delegate的新手,我正在尝试创建一个简单的类来与他们一起工作。我希望该类的实例能够将函数作为参数,将其存储在委托中,然后在外部源提示时调用该委托。比如: class UsesDelegates { private delegate void my_delegate_type(); private my_delegate_type del; public void GetDelegate ( /*Not sure what goes here*/ ) {.

我是C#delegate的新手,我正在尝试创建一个简单的类来与他们一起工作。我希望该类的实例能够将函数作为参数,将其存储在委托中,然后在外部源提示时调用该委托。比如:

class UsesDelegates {

    private delegate void my_delegate_type();
    private my_delegate_type del;

    public void GetDelegate ( /*Not sure what goes here*/ ) {...}
    public void CallDelegate () {
         del();
    }
}
我遇到的问题是,由于
my\u delegate\u type
是类的内部类型,因此无法在类外部构造它,以便将其传递给
GetDelegate()
。我希望能够将函数名作为字符串传递给
GetDelegate()
,以便可以在方法中构造委托,但我找不到这样做的方法。我意识到我可以将
my_delegate\u type
设置为全局,并在该类之外构造委托,但将该类型设置为全局似乎不合适,因为它仅由
UsesDelegates
使用。是否有一种方法可以在实现所需功能的同时封装类型?

您需要使用代理而不是
代理,如下所示

public class UsesDelegates
{
    private Action action;

    public void GetDelegate(Action action) => this.action = action;
    public void CallDelegate() => del();
}
然后您可以使用它,如下所示:

class Program
{
    static void Main(string[] args)
    {
        UsesDelegates usesDelegates = new UsesDelegates();
        usesDelegates.GetDelegate(Console.WriteLine);
        usesDelegates.CallDelegate();
    }
}
Action
通过传递类型来支持参数,如:
Action
,如果需要返回类型,可以使用
Func