C# How to call something from within a class metho

2020-04-01 08:12发布

I have some code that produces this compiler error:

CS0236 A field initializer cannot reference the non-static field, method, or property 'PublicModule.rnd'

The code is below, with the line with the error marked:

public class PublicModule : ModuleBase
{
    Random rnd = new Random();
    int value = rnd.Next(4,50); // <<<< Error is here

    [Command("Ping")]
    public async Task ping()
    {
       await ReplyAsync(Context.User.Mention + ", Pong!");
    }

    [Command("Hara")]
    public async Task hara()
    {
        await ReplyAsync("Hara noi te iubim <3 .");
    }

    [Command("kek")]
    public async Task kek()
    {
        await ReplyAsync(Context.User.Mention + ", kek");
    }

    [Command("Random")]
    public async Task Dice()
    {
        await ReplyAsync(Context.User.Mention + " ur random number is : " + value);
    }
}

How can I call that rnd.Next from a class? I'm noob at coding and I don't know how can I call things from another class or function etc.

标签: c#
2条回答
Bombasti
2楼-- · 2020-04-01 08:26

Put it in the constructor:

Random rnd = new Random();
int value;

public PublicModule()
{
    value = rnd.Next(4,50); 
}

But I should also point out that this will only give you a new random number once per class instance. If you want a different random number every time you call the function, you should do it like this:

[Command("Random")]
public async Task Dice()
{
    int value = rnd.Next(4,50);
    await ReplyAsync(Context.User.Mention + " ur random number is : " + value);
}
查看更多
霸刀☆藐视天下
3楼-- · 2020-04-01 08:29

Remove the statement int value = rnd.Next(); from the class and move it to the function Dick() as follows:

public async Task Dice()
{
    int value = rnd.Next(4, 50);
    await ReplyAsync(Context.User.Mention + "ur random number is: " + value);
}

Hope it helps.

查看更多
登录 后发表回答