【问题标题】:C# Calling methods inside of a generic method by comparing T with MyClassesC# 通过比较 T 和 MyClasses 在泛型方法中调用方法
【发布时间】:2022-06-10 21:26:33
【问题描述】:

我有一些课程,例如:

class Contract
{
    public int id;
    public string num;
    public double value;
    public bool isnew;
    public bool toupdate;
    ...
}

class Attachment
{
    public int id;
    public int year;
    public int finance;
    public double value;
    ...
}

当我调用MySqlDataReader.Read() 时,我想通过一个通用函数调用它,该函数返回一个列表。而不是为每个类创建一个方法,我想要这样的东西:

public List<T> ReadAs<T>()
{
    List<T> result;
    switch (T){
        case Contract: { result = ReadAsContract(); DoSomething1(); break; }
        case Attachment: { result = ReadASAttachment(); DoSomething2(); break; }
    }
    return result;
}

private List<Contract> ReadAsContract() {...here i make call MySqlDataReader.Read() and make list of instances...}
private List<Attachment> ReadAsAttachment() {...here i make call MySqlDataReader.Read() and make list of instances...}

所以我的问题是,是否有可能制作像我描述的那样的东西?还是最好制作大量 ReadAsMyClass 方法并每次调用准确的方法?

【问题讨论】:

  • 只使用 Dapper,不要重新发明你自己的 micro-orm ...它有很好的 DbConnection.Query&lt;T&gt;(...) 扩展方法

标签: c# class generics types


猜你喜欢
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
相关资源
最近更新 更多