开发者

define and initialize a list containing a struct with a func<> member

开发者 https://www.devze.com 2023-02-13 04:31 出处:网络
I have got a List<Problem> which I want to export to a column based file format (excel in my case).

I have got a List<Problem> which I want to export to a column based file format (excel in my case).

So for each data member of my Problem class there is a corresponding column in my file.

Each column has got a header (string) and a function which will get that the row-value from a class Problem object (which can be of type string, double or DateTime).

To define the relation from Problem object to column I use a class like this:

private class ExportColumn<T>
{
    public ExportColumn (string colHeader, Func<Probleme, T> colGetter)
    {
        header = colHeader;
        getValue = colGetter;
    }

    public string header;
    // This function will return the row value for th开发者_运维技巧at column for one problem
    public Func<Probleme, T> getValue; 
}

How can I define a list of many ExportColumns, to iterate over and extract all the row data for all problems?

Something like this (pseudocode):

private static string GetThema(Probleme problem)
{
    return problem.Thema;
}

private static double GetStatus(Probleme problem)
{
    return problem.Status + 100;
}

private static readonly List<ExportColumn> colList = new List<ExportColumn> 
{
    ("Thema", GetThema),
    ("Status", GetStatus)
    ...
};

foreach(ExportColumn col in colList)
{
    foreach(Problem problem in Probleme)
    {
        WriteToFile(col.header, col.getValue(problem))
    }
}

I'm pretty new to C#, so perhaps this is the wrong way to solve that issue. Basically I just want one place in my code, where I define all headers, the corresponding function which will extract the value from a problem in a typesafe way.

Thanks for any help!

EDIT: In C++ words: I would like a vector of class ExportColumn which contain a string and a function pointer to a getter method with that signature : T getValue(const Problem &problem)


You can't do that, if the supplied generic parameter changes. You will need to create the struct without generics:

class ExportColumn
{
    public ExportColumn (string colHeader, Func<Probleme, object> colGetter)
    {
        Header = colHeader;
        GetValue = colGetter;
    }

    public string Header {get; private set;}
    // This function will return the row value for that column for one problem
    public Func<Probleme, object> GetValue {get; private set;}
}

Instances of this struct can now be put into a List<ExportColumn>. You could initialize that list like so:

List<ExportColumn> colList = new List<ExportColumn> 
{
    new ExportColumn("Thema", p => p.Thema),
    new ExportColumn("Status", p => p.Status + 100)
};
0

精彩评论

暂无评论...
验证码 换一张
取 消