C# 字段初始值设定项无法引用loginController中的非静态字段、方法或属性

C# 字段初始值设定项无法引用loginController中的非静态字段、方法或属性,c#,asp.net,asp.net-mvc,model-view-controller,random,C#,Asp.net,Asp.net Mvc,Model View Controller,Random,我是c#MVC的初学者,我编写了一个类randomgenerator来生成随机数 public class RandomGenarator { public int rand() { Random rnd = new Random(); int i = rnd.Next(100); return i; } } 但是当我试图在我的控制器类中使用它时 public class LoginController : Contr

我是c#MVC的初学者,我编写了一个类
randomgenerator
来生成随机数

public class RandomGenarator
{

    public int rand()
    {
        Random rnd = new Random();
        int  i = rnd.Next(100);
        return i;
    }
}
但是当我试图在我的控制器类中使用它时

public class LoginController : Controller
{ 
    RandomGenarator rnd = new RandomGenarator();
    int i = rnd.rand();

    public ActionResult Index()
    {

        return View();
    }
 }
我面临着这个错误:

字段初始值设定项不能引用非静态字段、方法或属性


这是因为您没有尝试调用方法
inti=rnd.rand()在控制器的方法(或)构造函数中

public class LoginController : Controller
{ 
    private RandomGenarator rnd = null;

    public LoginController()
    {
       rnd = new RandomGenarator();
    }

    public ActionResult Index()
    {
     int i = rnd.rand();
     return View();
    }
}

将代码移到
public ActionResult Index()

中错误有线索,既然您正在学习,让我们将其分解

A field initializer
该字段为int i。它是类中的一个字段,而不是属性,因为没有getter或setter

cannot reference
您不能在此字段上使用=

the nonstatic
equals的另一侧,即引用的目标,不是静态的。如果是静态的话呢

field, method, or property
这是我“引用”的目标,它是非静态对象rnd上的方法rand()


因此,错误是不能将i设置为非静态的值。

初始化构造函数中的字段
i
public LoginController(){i=rnd.rand();}
还应注意,每次需要随机数时,不应创建一个
new Random()
对象以避免重复数。创建一个这样的对象,将其保存在内存中,然后每次都使用它来执行
。下一步(…)
。非常感谢,但我使用生成一个随机数,将其保存为整数,并在不同的操作中使用。例如,在您的代码中,我不能在另一个ActionResult中使用i。非常感谢,但我使用生成一个随机数,将其保存在整数中,并在不同的操作中使用。例如,在您的代码中,我不能在另一个ActionResult中使用i。