I want to declare var keyword in globally for the variable in mvc controller Because I am using that variable at multiple times thats why I want to use that variable as a globally. But I dont know that how var is been done by globally because var is different type as per string, int, decimal to place in globally.
For more clear lets see the code
var query = new List<T>();
if (model.CategoryId == -1)
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
else
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true && w.CategoryId == model.CategoryId).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
var dataList = (from x in query
select new
{
})
Now, here query variable is used many times in code. Now, I want to declare globally this query variable. This is the latest code that I tried. In this error is showing by giving red line in code.
答案 0 :(得分:1)
首先,您的“全局”定义不清楚。您要对一个类使用“查询”实例还是要对一个类生成的所有类使用。
第二,如果要用作全局变量,则应这样定义全局变量
List<dynamic> query=new List<dynamic>();
当然,这种方法不是健康的方法(与c#一起动态使用)
顺便说一句,您不能在函数外使用“ var”关键字。您必须在类级别使用某种类型的变量目标。
在课程级别定义变量
在给定的代码段中,我尝试在类级别定义全局变量。
public class MyTestClass
{
List<dynamic> query=new List<dynamic>();
public MyTestClass()
{
}
public void generateQuery()
{
if (model.CategoryId == -1)
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
else
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true && w.CategoryId == model.CategoryId).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
var dataList = (from x in query
select new
{
})
}
}
}
让我们尝试介绍另一种方法。
将生成的类的变量用作全局变量
这时您可以在祖先类中定义全局变量
public class MyAncestorClass
{
List<dynamic> query=query=new List<dynamic>();
}
public class MyChildClass:MyAncestorClass
{
public void generateQuery()
{
if (model.CategoryId == -1)
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
else
{
query = _Db.Purchase.Where(w => w.IsIncludeIntoStock == true && w.CategoryId == model.CategoryId).ToList().GroupBy(x => new { x.ManufacturerId, x.CategoryId, x.Weight, x.WeightTypeId }).ToList();
}
var dataList = (from x in query
select new
{
})
}
}
}