Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从c中的泛型创建对象#_C#_Unit Testing_Generics - Fatal编程技术网

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

C# 如何从c中的泛型创建对象#,c#,unit-testing,generics,C#,Unit Testing,Generics,我试图用相同的方法测试几个类,但逻辑不同,所以我想创建一个通用的测试用例。如何实例化泛型方法 我的例子是: [TestClass] public class GenericTest<T : MyBuilder> { T target; [TestInitialize()] public void MyTestInitialize() { target = new T(param1, param2, param3, param4); // here i'm

我试图用相同的方法测试几个类,但逻辑不同,所以我想创建一个通用的测试用例。如何实例化泛型方法

我的例子是:

[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();
}
[TestClass]
公共类通用测试
{
T靶;
[测试初始化()]
公共无效MyTestInitialize()
{
target=new T(param1,param2,param3,param4);//我显然被卡住了
}
[测试方法]
公共void TestMethodBuilder()
{
AreEqual(GetNameAsItShouldBe(),target.BuildName());
}
抽象公共字符串getnameashouldbe();
}

那么我如何实例化这个类呢?我有很强的Java背景,因此我的代码可能与c不兼容。

对于带有参数的构造函数,必须使用反射:

public class GenericTest<T> where T : MyBuilder
{
    [TestInitialize]
    public void Init()
    {
        target = (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2, param3, param4 });
    }
}
public类GenericTest其中T:MyBuilder
{
[测试初始化]
公共void Init()
{
target=(T)Activator.CreateInstance(typeof(T),新对象[]{param1,param2,param3,param4});
}
}

您还可以指定T具有无参数构造函数

public class GenericTest<T : MyBuilder> where T: new()
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>