简体   繁体   English

如何在C#中从泛型创建对象

[英]How to create an Object from Generics in c#

Im trying to test a few classes with the same methods but different logic, so i want to create a testcase which is generic. 我试图用相同的方法但逻辑不同的方法测试一些类,所以我想创建一个通用的测试用例。 how can i instantiate the generic methode? 我该如何实例化泛型方法?

My Example: 我的例子:

[TestClass]
public class GenericTest<T : MyBuilder>
{
  T target;

  [TestInitialize()]
  public void MyTestInitialize()
  {
      target = new T(param1, param2, param3, param4); // here i'm obviosly stuck
  }

  [TestMethod]
  public void TestMethodBuilder()
  {
      Assert.AreEqual<string>(GetNameAsItShouldBe(),target.BuildName());
  }

  abstract public string GetNameAsItShouldBe();
}

So how can i instantiat the class? 那么我该如何实例化课程呢? I've a strong Java background, so my code is may not c# compatible. 我具有较强的Java背景知识,因此我的代码可能与c#不兼容。

For a constructor with parameters you have to use reflection: 对于带有参数的构造函数,必须使用反射:

public class GenericTest<T> where T : MyBuilder
{
    [TestInitialize]
    public void Init()
    {
        target = (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2, param3, param4 });
    }
}

You can also specify that the T has a parameterless constructor 您还可以指定T具有无参数构造函数

public class GenericTest<T : MyBuilder> where T: new()

This will ensure that your T has a default constructor and allow you access to it in your TestInitialize . 这将确保您的T具有默认构造函数,并允许您在TestInitialize对其进行访问。 See http://msdn.microsoft.com/en-us/library/d5x73970.aspx 请参阅http://msdn.microsoft.com/en-us/library/d5x73970.aspx

If however you don't want to specify that then you can define a factory method on your T, ie 但是,如果您不想指定该参数,则可以在T上定义一个工厂方法,即

interface IBuildGenerically<T1, T2, T3, T4>
{
    T Build(T1 param1, T2 param2, T3 param3, T4 param4);
}

public class GenericTest<T : MyBuilder> 
  where T: IBuildGenerically<int, string, int, bool>

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

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