C# 在API类中使用类中的函数
我想通过从另一个类调用函数来设置API类中的一些数据 为什么“类”工作时“主”有错误?我应该如何以及在哪里定义它? 错误:字段初始值设定项无法引用非静态字段 我如何才能获得传递到URL中的ID,以便在我的类中使用 这是我的代码:C# 在API类中使用类中的函数,c#,asp.net-web-api,C#,Asp.net Web Api,我想通过从另一个类调用函数来设置API类中的一些数据 为什么“类”工作时“主”有错误?我应该如何以及在哪里定义它? 错误:字段初始值设定项无法引用非静态字段 我如何才能获得传递到URL中的ID,以便在我的类中使用 这是我的代码: public class InformationController : ApiController { Classes main = new Classes(); Information[] Information = new Information
public class InformationController : ApiController
{
Classes main = new Classes();
Information[] Information = new Information[]
{
new Information { Info_ID = 2, fullName = main.getFullname("2"), },
};
public IEnumerable<Information> GetAllInformation()
{
return Information;
}
public Information GetInformationById(int id)
{
var information = Information.FirstOrDefault((p) => p.Info_ID == id);
if (information == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return information;
}
public IEnumerable<Information> GetInformationByCategory(string category)
{
return Information.Where(
(p) => string.Equals(p.std_nextClass, category,
StringComparison.OrdinalIgnoreCase));
}
}
您可以尝试在构造函数中初始化数组: 公共类信息控制器:ApiController { 私有类主类=新类; 私人信息[]信息; 公共信息控制员 { 信息=新信息[] { 新信息{Info_ID=2,fullName=main.getFullname2,}, }; } ///剩下的代码。。。
你能详细解释一下为什么main不工作吗?调用main.getFullname2时是否出错?类的实现看起来如何?main是调用非静态函数的类的实例。你能展示类的实现吗?我认为,你将getFullname方法定义为static,你应该删除static关键字