C# - 类在方法中键入参数

时间:2011-01-11 00:33:59

标签: c#

我正在使用SQLite.cs包装器来帮助我使用数据库,我有这种方法可以从表中创建XML,这样工作正常。

public void GenerateInvoiceXML(string filePath) {
        var invoices = app.db.Table<Invoice>().ToList();

        XmlSerializer serializer = new XmlSerializer( typeof(List<Invoice>) );
        TextWriter writer = new StreamWriter(filePath);

        serializer.Serialize(writer,invoices);
        writer.Close();

}

我所有的表都是这样定义的:

[Serializable]  
public class Invoice
{

    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Supplier {get; set;}
    public string Date {get; set;}
    public string PaymentMethod {get; set;}
    public string Notes {get; set;}

    public Invoice(int newID)
    {
        Id = newID;
    }
    public  Invoice()
    {

    }
}

但是我想改变这种方法:

public void GenerateInvoiceXML(string filePath, Type table) {
        var dataForXML = app.db.Table<table>().ToList();

        XmlSerializer serializer = new XmlSerializer( typeof(List<table>) );
        TextWriter writer = new StreamWriter(filePath);

        serializer.Serialize(writer,dataForXML);
        writer.Close();     
}

有人知道怎么做吗?

亲切的问候,
克劳迪奥

2 个答案:

答案 0 :(得分:6)

试试这个:

public void GenerateInvoiceXML<TTable>(string filePath) {
    var dataForXML = app.db.Table<TTable>().ToList();

    XmlSerializer serializer = new XmlSerializer( typeof(List<TTable>) );
    TextWriter writer = new StreamWriter(filePath);

    serializer.Serialize(writer,dataForXML);
    writer.Close();     
}

为了传递泛型类型参数,您必须能够将其指定为编译时 - 为了做到这一点,您必须使GenerateInvoiceXML方法具有通用性,如上所示。

答案 1 :(得分:2)

你可以试试这个:

public void GenerateXML<T>(string filePath)
{
    var dataForXML = app.db.Table<T>().ToList();
    XmlSerializer serializer = new XmlSerializer( typeof(List<T>) );
    TextWriter writer = new StreamWriter(filePath);
    serializer.Serialize(writer,dataForXML);
    writer.Close();
}