c# - 字段初始值设定项不能引用 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();
}
}
我面临这个错误:
“字段初始值设定项不能引用非静态字段、方法或属性”
解决方案
那是因为您没有尝试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();
}
}
推荐阅读
- data-science - One-Hot 编码或不 One-Hot 编码
- merge - UML 2.5:在包合并中同名但不同类型的属性会发生什么?
- ios - 配置 UICollectionViewDataSourcePrefetching 范围
- python - Librosa 的 fft 和 Scipy 的 fft 不一样?
- oauth-2.0 - IdentityServer4授权代码流同意页面的最佳实践?
- javascript - 使用 Javascript 按 ID 查找两个元素
- cypress - 赛普拉斯获取元素长度返回双倍
- entity-framework - 每次我在数据库中进行更改时是否需要更新代码/应用程序?
- sql - 删除 Oracle SQL 中的重复行
- xamarin.android - 预加载 DialogFragment