gpt4 book ai didi

c# - 将查询结果存储到变量中

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:52 25 4
gpt4 key购买 nike

我是 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; } - 不推荐,因为它会增加运行时错误的风险并降低可读性

3) 使用tuples (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));
}

关于c# - 将查询结果存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57645268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com