首页 > 解决方案 > 如何使用 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# 中做到这一点?

标签: 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)
    {
        
    }
}

类的部分可用于初始化是有顺序的。在构造函数运行之前声明字段,然后构造函数运行。在构造函数运行之前,字段不能引用类上的任何其他实例字段或方法。


推荐阅读