I have a built an XML parser which parses different types of products. The parser code is common for all product types (it deserializes the XML into Product type)
So I have created a generic base class called XmlParser
public abstract class XmlParser<TProduct> where TProduct : ProductBase
{
public abstract TEntity Instanciate();
private string _parserName;
public XmlParser(string parserName)
{
_parserName = parserName;
}
public List<TProduct>Parse()
{
TEntity product = Instanciate(); // <-- I need to instantiate the Generic type here
// deserialize XML into product
}
}
and a derived class:
public class CarXmlParser : XmlParser<Car>
{
public CarXmlParser() : base("CarParse") {}
public override Car Instanciate()
{
return new Car();
}
}
Car
is product type and is derived from ProductBase
In the base class, I need to instantiate TProduct
. The only way I could do this was by creating an abstract method in the base class: public abstract TEntity Instanciate();
. Obviously the child has to implement it.
Is there an easier way to instantiate the generic type? I have seen this question where they use new T
constraint for the same purpose, however I was not able apply it to my example...
If it has a default constructor , add the New Constraint , and new
it up
The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
Example
public abstract class XmlParser<TProduct>
where TProduct : ProductBase, new()
...
public List<TProduct>Parse()
{
var product = new TProduct();
...
如果它没有new()
约束,您可以使用以下内容:
Activator.CreateInstance<T>();
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.