简体   繁体   中英

Calling a generic function in C#

I try to do a generic function of this

    networking.Ssl_Elts = (from line in allLines
                           let data = line.Split(',')
                           where line.Substring(0, Len("SSL_ELT,")) == "SSL_ELT,"
                           select new SSL_ELT(data)
                           ).ToList();

    networking.Ssl_Headers = (from line in allLines
                              let data = line.Split(',')
                              where line.Substring(0, Len("SSL_HEADER,")) == "SSL_HEADER,"
                              select new SSL_HEADER(data)
                              ).ToList(); 

By doing this:

public List<T>GetObjects<T> (IEnumerable<string> allLines,string ObjectName)
{
    var result =  (from line in allLines
            let data = line.Split(',')
            where line.Substring(0, Len("SSL_HEADER,")) == "SSL_HEADER,"
            select new T(data)).ToList();
    return (T)result;
}

So I would be able to call this function passing only:

networking.Ssl_Headers = GetObjects<Ssl_Headers>(allLines, "SSL_HEADER");

But it doesn't work.

Any idea.

Thanks in advance

You can't call new T(data) , because not every type has a constructor accepting a single argument of type string[] , however, you could use a factory function:

public List<T> GetObjects<T>(IEnumerable<string> allLines, string objectName,
    Func<string[], T> factory)
{
    objectName += ",";
    return (from line in allLines
        let data = line.Split(',')
        where line.Substring(0, Len(objectName)) == objectName
        select factory(data)).ToList();
}

Which can be called like this:

networking.Ssl_Headers = GetObjects(allLines, "SSL_HEADER", x => new Ssl_Headers(x));

And, as mentioned in the comments by @DragAndDrop, using string.StartsWith would be simpler:

public List<T> GetObjects<T>(IEnumerable<string> allLines, string objectName,
    Func<string[], T> factory)
{
    return (from line in allLines
        let data = line.Split(',')
        where line.StartsWith(objectName + ",")
        select factory(data)).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM