General method: create a typical type with an argument

I have a generic method that accepts a type T, which should be able to call a constructor that requires one XmlNode. I'm currently trying to do this by having an abstract base class with the constructors I want (plus without parameters, so I don't need to edit the “subclasses” other than adding the actual subclass) and hold back this. If I try to instantiate one of these classes, it complains that it:

Cannot create an instance of the variable type 'T' because it does not have the new() constraint

and if I add a restriction new(), I get:

'T': cannot provide arguments when creating an instance of a variable type

How can I do what I want?

+3
source share
2 answers
+3

, T . , , , overriden (, ).

new() . (, IConstructFromXml), , - .

, factory . factory . - :

void Foo<TFactory, T>() where TFactory : IFactory<T> 
                        where TFactory : new() {
   var factory = new TFactory();
   T val = factory.Create(xmlNode); // Create method is defined in IFactory<T>
   // ...
}

IFactory<T> :

interface IFactory<T> {
  T Create(XmlNode node);
}   

Foo , factory ( ), , ..

+2

Source: https://habr.com/ru/post/1756393/


All Articles