[英]Extending a Class with a method on runtime
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.我想创建一个
Testcase
对象List
,但我不喜欢为每个Testcase
创建一个对象。 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();
}
The closest you can get is to use the Dynamic Language Runtime features with an ExpandoObject
.您可以获得的最接近的是将动态语言运行时功能与
ExpandoObject
一起使用。
dynamic d = new ExpandoObject();
d.Quack = (Action)(() => System.Console.WriteLine("Quack!!!"));
d.Quack();
There are many downsides to this though, including lack of InteliSense, no compiler errors when accessing non-existent members, and poor performance,但这有很多缺点,包括缺乏 InteliSense,访问不存在的成员时没有编译器错误,以及性能不佳,
I found the following post: Dynamically assign method / Method as variable with that I could a assign a "dummy" Method to my Testcase Class and could assign a Test workflow to it on the runtime.我找到了以下帖子: 动态分配方法/方法作为变量,我可以为我的测试用例类分配一个“虚拟”方法,并可以在运行时为其分配一个测试工作流。 For someone who has the same usecase the code:
对于具有相同用例的人,代码:
public class TestCase
{
public string title;
public TestCase(string Title)
{
title = Title;
}
public Action dummyMethod{ get; set; }
}
public void realMethod()
{
System.Console.WriteLine("testSuccesfull");
}
public initTestcollection()
{
AddTestCases();
T1.TestcaseList[0].dummyMethod= realMethod;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.