如何在c#中将方法指定为参数?

如何在c#中将方法指定为参数?,c#,unity3d,C#,Unity3d,我有一个类,它创建一个从100倒计时到0(由随机值递减)的数字列表 我的目标是将此方法应用于类的实例(其中列表是参数之一)。然而,我也不认为这是最有效的方法。我对c#/编码相当陌生,所以任何建议都非常好!这是我的密码: public class Emotion { readonly string name; readonly List<int> statusChange; public Emotion(string name, List<int>

我有一个类,它创建一个从100倒计时到0(由随机值递减)的数字列表

我的目标是将此方法应用于类的实例(其中列表是参数之一)。然而,我也不认为这是最有效的方法。我对c#/编码相当陌生,所以任何建议都非常好!这是我的密码:

public class Emotion
{
    readonly string name;
    readonly List<int> statusChange;
    public Emotion(string name, List<int> statusChange)
    {
        this.name = name;
        this.statusChange = statusChange;
    }

    static void Main(string[] args)
    {
        numberGenerator();
        Emotion Hunger = new Emotion("Hunger", numberGenerator());
        
    }

    static List<int> numberGenerator()
    {
        List<int> numberGen = new List<int>();
        numberGen.Add(100);
        Random r = new Random();


        while (numberGen.Last() != 0)
        {
            int lastInt = numberGen.Last();
            int rInt = r.Next(1, 15); //might change the range 
            int newValue = lastInt - rInt;
            numberGen.Add(newValue);
        }

        //prints out list as a string
        Console.WriteLine(String.Join(",", numberGen));

        return numberGen;
    }
}
公共课堂情感
{
只读字符串名称;
只读列表状态更改;
公众情绪(字符串名称、列表状态更改)
{
this.name=名称;
this.statusChange=statusChange;
}
静态void Main(字符串[]参数)
{
numberGenerator();
情感饥饿=新的情感(“饥饿”,numberGenerator());
}
静态列表编号生成器()
{
List numberGen=新列表();
数字加(100);
随机r=新随机();
while(numberGen.Last()!=0)
{
int lastin=numberGen.Last();
int rInt=r.Next(1,15);//可能会更改范围
int newValue=lastInt-rInt;
number.Add(新值);
}
//将列表打印为字符串
Console.WriteLine(String.Join(“,”,numberGen));
返回号码;
}
}

(我知道一些c#约定在我的代码中也可能是错误的!我将在解决此问题后进行修复)

为了实现您想要的结果,您需要了解委托

委托是用C#发送方法的方式。请阅读文档中的相关内容:

作为旁注,如果您的数字生成器处于紧密循环中,那么它很可能会生成重复的数字,因为您正在方法内部创建一个新的
Random
。将random作为类的私有字段。您需要为此创建一个值。您如何知道您的最后一个整数将精确地达到零?似乎它可以跳过零并进入负区域,导致无限循环。@JohnWu仅在到达
int.MinValue
:P。。但是是的,你应该做一些像
intnewvalue=Mathf.Max(lastInt-rInt,0)