public interface IParser<T> where T: new()
{
IList<T> Parse();
}
The following abstract class is implemented over the interface.
public abstract class BaseParser<T>: IParser<T> where T : new()
{
protected abstract string Sql { get;}
public List<T> Parse()
{
Console.WriteLine(Sql);
}
}
Below are two specific implementations of the above abstract class
public class EMailParser: BaseParser<Email>
{
protected override string Sql
{
get
{
return @"SELECT * FROM emails";
}
}
}
public class UrlParser : BaseParser<Url>
{
protected override string Sql
{
get
{
return @"SELECT * From Url";
}
}
}
Using:
class Program
{
static void Main(string[] args)
{
if(args[1] == "url")
Parser<Url>();
else
Parser<Email>();
}
static void Parse<T>()
{
IParser<T> parser = typeof(T) == typeof(Url) ? new UrlParser(): new EmailParser();
parser.Parse();
}
}
I want to create an instance of the database EmailParseror UrlParserfor the general type provided in Program.Main, and assign it to the interface implemented BaseParser(abstract class). How can i do this? I know I can solve this problem by changing Program.Parse<T>as follows
static void Parse<T>() where T: new()
{
IParser<T> parser = typeof(T) == typeof(Url) ? new UrlParser() as BaseParser<T> : new EmailParser() as BaseParser<T>;
parser.Parse();
}
However, I want to know why I cannot assign an instance of a child class to an interface implemented by an abstract class?
I do not understand why the next line does not work
IParser<T> parser = typeof(T) == typeof(Url) ? new UrlParser(): new EmailParser();
and why does this line work
IParser<T> parser = typeof(T) == typeof(Url) ? new UrlParser() as BaseParser<T> : new EmailParser() as BaseParser<T>;
@nawfal, , BaseParser BaseParser - . IParser BaseParser?