[英]Storing query result into a variable
我是C#的初学者,对通用类型的正确理解有些麻烦。 在此示例中,我想以某种方式将查询结果存储到变量中。
我在下面显示的代码不正确,因为应该指定通用类型T。
public class Data
{
public IQueryable<T> Results { get; set; }
public Data()
{
var db = new Database();
}
public void Store()
{
Results = db.Products.Select(x => new { x.ProductName, x.Cost });
}
}
是否可以在不声明仅用于一种用途的特殊类的情况下做到这一点?
public class ProductView
{
public string ProductName { get; set; }
public int Country { get; set; }
}
...
public IQueryable<ProductView > Results { get; set; }
另外,为什么动态类型在此示例中不适合?
public dynamic Results { get; set; }
有3种方法可以解决此问题:
1)创建您提到的类似于ProductView
类-经典C#6或更旧的方式
2)使用dynamic
代替T
例如: public IQueryable<dynamic> Results { get; set; }
public IQueryable<dynamic> Results { get; set; }
public IQueryable<dynamic> Results { get; set; }
-不建议使用,因为它会增加运行时错误的风险并降低可读性
3)使用元组 (C#7功能):
public IQueryable<(string, int)> Results { get; set; } // I suppose ProductName is string and Cost is int
public void Store()
{
Results = db.Products.Select(x => (x.ProductName, x.Cost));
}
这里的问题是您的Data
类似乎了解有关T
一些特定知识。 在Store
方法中,它读取Products
并从每个项目中获得两个特定的属性。 因此,它实际上不是可以存储任何类型的泛型类。 非常具体。
要使其通用,您将需要删除Store
方法。 然后剩下的就不多了。 您需要确定Data
的用途是什么。 存在什么问题要解决?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.