Is there a possibility to add methods to an existing class at run time?
I want to create a List
of Testcase
objects and I don't like to create for each Testcase
an object. So I like to use a unique object without any method for the Test cases without any procedure info. I want to add this method afterwards.
Code:
public class Testcollection
{
public List<TestCase> TestcaseList = new List<TestCase>();
public string title;
public Testcollection(string Title)
{
title = Title;
}
}
public class TestCase
{
public string title;
public TestCase(string Title)
{
title = Title;
}
}
public class initTestcollection
{
public Testcollection T1 = new Testcollection("Collection1");
public Testcollection T2 = new Testcollection("Collection2");
public void AddTestCases()
{
T1.TestcaseList.Add(new TestCase("Test1"));
T1.TestcaseList.Add(new TestCase("Test2"));
}
//Pseudocode
public void inject_method_toT1()
{
Console.WriteLine("injected code A");
}
public void inject_method_toT2()
{
Console.WriteLine("injected code B");
}
//constructor
public initTestcollection()
{
AddTestCases();
inject_method_toT1();
inject_method_toT2()
}
}
void Main()
{
Testcollection MyCollection = new initTestblocks();
MyCollection.T1.TestcaseList[0].inject_method_toT1();
MyCollection.T1.TestcaseList[1].inject_method_toT2();
}