c# - 如何使用 Action 声明 c# 构造函数参数(就像在 C 中传递一个指向 func 的指针)
问题描述
我有这样的课
class Class1
{
public Class1(Action<string> Log)
{
Log("bla bla"); // to be output by project Log system
}
}
在主窗体项目中,我尝试将我的 Log 函数传递给 Class1,因此在其中,我可以拥有相同的 log 函数
public partial class Form1 : Form
{
Class1 MyClass = new Class1(Log); // ERROR !
public Form1()
{
InitializeComponent();
}
public void Log(string line)
{
rtb.Text += line + "\n";
}
...
...
}
但我得到了这个错误
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.Log(string)'
我只需要通过它的构造函数将 Log() 函数指针传递给其他类,就像在 CI 中将使用函数指针作为参数传递一样。
如果我理解正确的话,Action 只是一个“代表”的捷径,它总是返回 void 并且可以有一些参数。编译器应该知道 Log() 存在(因此,有一个地址)所以为什么我不能将它作为参数传递?
那么,我该如何在 C# 中做到这一点?
解决方案
您需要将声明移动到构造函数中。像这样:
public partial class Form1 : Form
{
private Class1 MyClass;
public Form1()
{
InitializeComponent();
MyClass = new Class1(Log);
}
void InitializeComponent()
{
throw new NotImplementedException();
}
public void Log(string line)
{
}
}
类的部分可用于初始化是有顺序的。在构造函数运行之前声明字段,然后构造函数运行。在构造函数运行之前,字段不能引用类上的任何其他实例字段或方法。
推荐阅读
- javascript - Vue 在每次选择框选择时调用 axios
- python - 如何将 Python API 请求保存到 .txt 文件
- android - MaterialComponents 中 AppCompat.Button.Borderless 的替代方案是什么?
- python - 使用 Python 将 JSON 嵌套到扁平化 JSON
- android - Android 定期 Worker 停止重复,并且地理围栏在几天后停止触发
- spacy - 如何合并spacy Vocab实例?
- javascript - 选中复选框和“下一步”按钮后重定向到链接
- java - spring application.properties中的resilience4j.circuitbreaker.configs与resilience4j.circuitbreaker.backends有什么区别
- salt-stack - 如何在 saltstack 状态下查询外部 Web 服务并将值赋给变量
- python - 带有 force_list 参数的 xmltodict 为空 XML 列表返回一个带有 None 元素的列表