简体   繁体   English

C#中的泛型构造函数

[英]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)
  {
   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. 更新T可以是类型或值,因此对某些类型使用new()是好的,但是对于值不是。 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? 例如,是否可以传递类似于新T的东西(虽然它不应该,因为当时不知道T)或者什么是扭曲以避免传递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); 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM