I am trying to create a parser framework for XML strings containing SQL query results. The intent is to inherit from generic classes, which are instantiated with the column data types. The included code is for the single-column variety. There will be additional classes for two columns, etc.
I need to be able to specify that the generic type must support the Parse(string) method. How do I do this?
abstract class OneColumnParser<Col1>
{
abstract string Column1;
List<Col1> ParseQueryResult(string queryResult)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(queryResult);
List<Col1> results = new List<Col1>();
foreach (XmlNode xNode in xDoc.GetElementsByTagName(Column1))
{
results.Add(Col1.Parse(xNode.InnerText));
}
}
}
When I compile the above, I get “‘Col1’ is a ‘type parameter’, which is not valid in the given context” on the results.Add() line, because I haven’t specified that the type must support the method. But how?
Because interfaces can’t have static methods, you can’t (directly) do what you’re asking. Reflection is one way of solving the problem, but it’s only verified at runtime, not enforced by the compiler. E.g.
Unlike defining your own interface, this will work on existing types with
Parsemethods, such asintandDateTime. Update added code so that it will work onstringas well.