【问题标题】:Remove redundancies with multiple object types删除具有多种对象类型的冗余
【发布时间】:2019-04-04 05:18:41
【问题描述】:

我有一个从 SQLite 查询中选择一些属性的函数。该函数返回例如静态列表<Requests>。它工作得很好,唯一的问题是我需要这个函数来操作许多不同的对象,比如 cnn.Query<Requests>、cnn.Query<Responses> 等等。所以我不想为 20 个不同的对象调用这个函数 20 次。

谁能告诉我如何使这些<Requests><Responses> 动态化,只调用一次函数?

两倍几乎相同的功能,我想减少到一个:

public static List<Requests> ReadRequests(SQLiteCommand command)
        {
            using (IDbConnection cnn = new SQLiteConnection(command.Connection))
            {
                var output = cnn.Query<Requests>("select * from Requests", new DynamicParameters());
                return output.ToList();
            }
        }
        public static List<Responses> ReadResponses(SQLiteCommand command)
        {
            using (IDbConnection cnn = new SQLiteConnection(command.Connection))
            {
                var output = cnn.Query<Responses>("select * from Requests", new DynamicParameters());
                return output.ToList();
            }
        }

【问题讨论】:

  • So I dont want to call this function 20 times for 20 different objects 没有代码可以读懂你的想法,无论哪种方式,你都必须实现一个类型和一个查询字符串。请更具体,因为这有点太宽泛了

标签: c# sqlite simplification


【解决方案1】:

你可以做一个泛型类(参考这里的教程http://dotnetpattern.com/csharp-generics)。不过,您仍然需要每次都构建和调用该类。

例如:

public class GenericClass<T>
{
    public  List<T> ReadT(SQLiteCommand command)
    {
        using (IDbConnection cnn = new SQLiteConnection(command.Connection))
        {
            var output = cnn.Query<T>("select * from "+typeof(T).Name, new DynamicParameters());
            return output.ToList();
        }
    }
}

附:代码没有测试,仅供参考。

【讨论】:

  • 完美!我正是在找这个,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多