将随机转换为int visual studio 2015

Tal*_*dad -2 c# random winforms visual-studio-2015

为什么这不起作用?它是在视觉研究2015年,Windows窗体应用程序C#

namespace guessing
{
    public partial class Form1 : Form
    {
        Random rnd = new Random();
        int rndm = rnd.Next(1, 13);
Run Code Online (Sandbox Code Playgroud)

在rnd下有一个错误,它说:

"字段初始值设定项不能引用非静态字段,方法或属性'Form1.rnd'"

Cee*_* it 6

在C#中,语句不能立即在类声明下发生.它们需要成为函数或方法的一部分.

namespace guessing
{
    public partial class Form1 : Form
    {
        void MethodX()
        {
            Random rnd = new Random();
            int rndm = rnd.Next(1, 13);
            /* to be continued... */ 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)