【问题标题】:Storing query result into a variable将查询结果存储到变量中
【发布时间】:2019-12-29 21:34:35
【问题描述】:

我是 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; }

【问题讨论】:

    标签: c# variable-types dynamictype


    【解决方案1】:

    有3种方法可以解决这个问题:

    1) 创建您提到的 ProductView 之类的类 - 经典 C#6 或更旧的方式

    2) 使用dynamic 而不是T,例如:public IQueryable&lt;dynamic&gt; 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));
    }
    

    【讨论】:

      【解决方案2】:

      这里的问题是你的Data 类似乎知道一些关于T 的具体事情。在Store 方法中,它读取Products 并从每个项目中获取两个特定属性。所以它实际上并不是一个可以存储任何类型的泛型类。非常具体。

      要使其通用,您需要删除 Store 方法。然后所剩无几。您需要确定Data 的目的是什么。存在什么问题需要解决?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        相关资源
        最近更新 更多