0

I would like to override a virtual base class function on the fly and use this overriden method in application. If I write a basic example class:

partial Class myBase
{
   public myBase() {}
   public virtual void DoStuff()
   {
      throw new Exception("this function is not overriden");
   }
}

partial Class myDeriv : myBase
{
   public myDeriv() {}
}

And now I would like to override myDeriv.DoStuff on the fly. So I create a string code block and compile it using

CSharpCodeProvider.CompileAssemblyFromSource

method. After writing this dll to disk I tried to load it using

Assembly.LoadFrom("onTheFly.dll");

But application fails to find this overridden function. If you have any other better solutions I'm open to them also.. I just need to override functions on the fly..

Thank you all!

4

1 回答 1

1

我认为这似乎不可能是由此处此处描述的相同规则引起的

引用原文:

“你不能在两个不同的程序集(项目)中有两个部分类引用同一个类。一旦程序集被编译,元数据就会被烘焙,你的类不再是部分的。部分类允许你拆分定义同一类的两个文件。”

或者

“您不能使用 partial 关键字在项目之间拆分类的代码。 partial 关键字是一种编译器技巧;编译器会从它找到的部分中输出一个类,因此该类的所有部分必须以相同的方式存在二进制文件。一旦类被编译,就没有留下它是部分类的痕迹。

如果您想扩展现有的类,您要么需要继承它(如果它不是密封的),要么创建您自己的新类,其中包含您希望从中组合信息的类。”

于 2011-12-30T14:54:18.600 回答