C# 委托和全局作用域
C# Delegates and Global Scoping
我是 C# 委托的新手,我正在尝试制作一个简单的 class 来处理它们。我希望 class 的实例能够将函数作为参数,将其存储在委托中,然后在外部源提示时调用该委托。类似于:
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_delegate_type
是 class 的内部,因此无法在 class 之外构造它以将其传递给 GetDelegate()
。我希望我能够将函数名称(可能作为字符串)传递给 GetDelegate()
,以便可以在方法内构造委托,但我找不到这样做的方法。我意识到我可以将 my_delegate_type
设为全局并在 class 之外构造委托,但将类型设为全局似乎不合适,因为它仅由 UsesDelegates
使用。有没有办法在保持类型封装的同时仍然实现所需的功能?
您需要使用 Action 而不是 delegate
,就像这样。
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<p1, p2>
,如果你需要return类型,你可以使用Func<return, p1, p2>
。
我是 C# 委托的新手,我正在尝试制作一个简单的 class 来处理它们。我希望 class 的实例能够将函数作为参数,将其存储在委托中,然后在外部源提示时调用该委托。类似于:
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_delegate_type
是 class 的内部,因此无法在 class 之外构造它以将其传递给 GetDelegate()
。我希望我能够将函数名称(可能作为字符串)传递给 GetDelegate()
,以便可以在方法内构造委托,但我找不到这样做的方法。我意识到我可以将 my_delegate_type
设为全局并在 class 之外构造委托,但将类型设为全局似乎不合适,因为它仅由 UsesDelegates
使用。有没有办法在保持类型封装的同时仍然实现所需的功能?
您需要使用 Action 而不是 delegate
,就像这样。
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<p1, p2>
,如果你需要return类型,你可以使用Func<return, p1, p2>
。