开发者

generic constructor in C#

I have the following:

GenericClass<T> : Class
{
  T Results {get; protected set;}
  public GenericClass<T> (T results, Int32 id) : base (id)
  {
    Results=results;
  }
  public static GenericClass<T> Something (Int32 id)
  开发者_Python百科{
   return new GenericClass<T> (i need to pass something like new T?, id); 
  }
}

Update T can be either type or value, so using new() is okish for some types but definetely not for values. I suppose that would imply some class redesign.

the idea was how to use the constructor? eg is it possible to pass something similar to new T (although it should not, because T is not known at the time) or what will to be the twist to avoid passing null?


This should work:

GenericClass<T> : Class where T : new()
{
  T Results {get; protected set;}
  public GenericClass<T> (T results, Int32 id)
  {
    Results=results;
  }
  public GenericClass<T> Something (Int32 id) : this(new T(), id)
  { }
}


class GenericClass<T> : Class where T : new()
{
  public T Results {get; protected set;}
  public GenericClass (T results, Int32 id) : base (id)
  {
    Results=results;
  }
  public static GenericClass<T> Something (Int32 id)
  {
   return new GenericClass<T> (new T(), id); 
  }
}


How about using reflection?

public static GenericClass<T> Something (Int32 id)
  {
   return new GenericClass<T> ((T)Activator.CreateInstance(typeof(T)), id); 
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜