所以我创建了一个将存储许多方法的类。然后打电话给他们 (忽略Unity 3D,因为这是一个c#问题)
using UnityEngine;
using System.Collections;
using System;
namespace Beast.Extensions
{
public class MethodList : MonoBehaviour
{
public MethodList (params System.Action[] _methods)
{
this.methods = new Action[_methods.Length];
}
public Action[] methods { get; set; }
/// <summary>
/// Calls a specific method in the list.
/// </summary>
/// <param name="method"></param>
public void Call (int method)
{
this.methods[method]();
}
/// <summary>
/// Calls all of the methods in this method group in order.
/// </summary>
public void CallAll()
{
int l = this.methods.Length;
for (int x = 0; x < l; x++)
{
this.methods[x]();
}
}
}
}
以下是我如何使用它并调用它。
MethodList deathMethods = new MethodList(() => print("Killing"), () => print("Dead"), () => Debug.Log("Dead a while ago."), () => print("Officially dead"));
deathMethods.Call(0); //Expected output: Killing
deathMethods.CallAll(); //Expected output: "Killing Dead a while ago Officially dead"
所有这些错误:
对象引用未设置为对象的实例
答案 0 :(得分:0)
ctor只创建数组,但不分配_methods的内容。
public MethodList(params Action [] _methods){
this.methods = _methods;
}
答案 1 :(得分:0)
这对我有用:
public MethodList(params Action[] methods)
{
Methods = methods;
}
public void Call(int num) => Methods[num]();
public void CallAll()
{
foreach (var method in Methods) method();
}
您必须将this.Methods
设置为method
。您只创建了一个大小为_method
的数组,但您没有对this.Methods
执行任何操作,因此它仍然是null
,您也没有对_method
中存储的值执行任何操作
您还可以添加索引器,如下所示:
public Action this[int index]
{
get { return Methods[index]; }
set { Methods[index] = value; }
}
并像这样使用它:
methodList[2] = () => Console.WriteLine("Alive again");
methodList[2]();