Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Work Around Limitations in Generic Type Constraints in C#?
    primarykey
    data
    text
    <p>Okay I'm looking for some input, I'm pretty sure this is not currently supported in .NET 3.5 but here goes. </p> <p>I want to require a generic type passed into my class to have a constructor like this:</p> <pre><code>new(IDictionary&lt;string,object&gt;) </code></pre> <p>so the class would look like this</p> <pre><code>public MyClass&lt;T&gt; where T : new(IDictionary&lt;string,object&gt;) { T CreateObject(IDictionary&lt;string,object&gt; values) { return new T(values); } } </code></pre> <p>But the compiler doesn't support this, it doesn't really know what I'm asking.</p> <p>Some of you might ask, why do you want to do this? Well I'm working on a pet project of an ORM so I get values from the DB and then create the object and load the values.</p> <p>I thought it would be cleaner to allow the object just create itself with the values I give it. As far as I can tell I have two options:</p> <p>1) Use reflection(which I'm trying to avoid) to grab the PropertyInfo[] array and then use that to load the values.</p> <p>2) require T to support an interface like so:</p> <p>public interface ILoadValues { void LoadValues(IDictionary values); }</p> <p>and then do this</p> <pre><code>public MyClass&lt;T&gt; where T:new(),ILoadValues { T CreateObject(IDictionary&lt;string,object&gt; values) { T obj = new T(); obj.LoadValues(values); return obj; } } </code></pre> <p>The problem I have with the interface I guess is philosophical, I don't really want to expose a public method for people to load the values. Using the constructor the idea was that if I had an object like this</p> <pre><code>namespace DataSource.Data { public class User { protected internal User(IDictionary&lt;string,object&gt; values) { //Initialize } } } </code></pre> <p>As long as the <code>MyClass&lt;T&gt;</code> was in the same assembly the constructor would be available. I personally think that the Type constraint in my opinion should ask (Do I have access to this constructor? I do, great!)</p> <p>Anyways any input is welcome.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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