Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is no way to specify that a generic type parameter <code>T</code> should have a constructor with a specified parameters. The fact that a base class has a constructor with some arguments doesn't help, because the overriden class doesn't <em>have to</em> have the same constructor (e.g. it can call the base constructor with some value as an argument).</p> <p>The <code>new()</code> constraint can be used to require a parameter-less constructor only. I would probably suggest adding an interface constraint (e.g. <code>IConstructFromXml</code>) that would have a method to initialize the object - then you can call the method after you create the object using a parameterless constructor.</p> <p>Alternatively, you could take a type parameter representing a factory for creating values of the specified type. Then you would create an instance of the factory and use it to create the value of the type you need. Something like:</p> <pre><code>void Foo&lt;TFactory, T&gt;() where TFactory : IFactory&lt;T&gt; where TFactory : new() { var factory = new TFactory(); T val = factory.Create(xmlNode); // Create method is defined in IFactory&lt;T&gt; // ... } </code></pre> <p>Where the <code>IFactory&lt;T&gt;</code> interface looks like this:</p> <pre><code>interface IFactory&lt;T&gt; { T Create(XmlNode node); } </code></pre> <p>Calling the <code>Foo</code> method is a bit more involved in this version, because you have to explicitly specify the factory (and you need to implement it as well), but it may be closer to what you want...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload