从静态类传递委托数组

问题描述

我正在尝试实例化一个类,该类从静态类的静态方法接受委托给 cunstructor(Func<string,bool>[]) 的数组,并抛出异常 System.ArgumentException: Delegate to an instance method cannot have null 'this'.

在静态类内部使用这个数组本身没有问题,只有当我尝试传递数组时才会发生异常。

public static class Program
{
    private static readonly MyAnotherClass MyAnotherField; // this is the error,see the answer below

    private static readonly Func<string,bool>[] UsefulMethods =
    {
        UsefulMethod1,// other methods
    }

    private static readonly MyClass MyClassField = new MyClass(UsefulMethods);

    public static void Main(string[] args)
    {
        MyClassField.Handle(); // exception occurs here
    }

    private static bool UsefulMethod1(string value)
    {
         // some logic
         return true;
    }
}

public class MyClass
{
    private readonly Func<string,bool>[] Methods;
    
    public MyClass(Func<string,bool>[] methods)
    {
        // guards
        Methods = methods;
    }

    public void Handle()
    {
        // some logic
    }
}

我错过了什么?

解决方法

所以我找到了解决方案。

示例在小提琴中无法重现,但在我的环境中,由于静态只读字段,我没有包含。

在上面的例子中也应该有一个字段:

private static readonly MyAnotherClass MyAnotherClassField;

没有在任何地方实例化。虽然我还是不明白,为什么会抛出关于委托的异常,做出这样的改变:

private static readonly MyAnotherClass MyAnotherClassField = new MyAnotherClass();

让一切正常。