首页 > 解决方案 > 字段初始值设定项不能引用 loginController 中的非静态字段、方法或属性

问题描述

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

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();
    }
 }

我面临这个错误:

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

标签: c#asp.netasp.net-mvcmodel-view-controllerrandom

解决方案


那是因为您没有尝试int i = rnd.rand();在控制器的方法 (OR) 构造函数中调用该方法。

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

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

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

推荐阅读