简体   繁体   中英

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.

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

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 . See 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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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