Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure if dynamically overriding a class's functionality is possible, but you can achieve something similar by using different interfaces. Depending on the context you want to use this in, it may require only small redesign.</p> <p>The standard way of doing it would be this:</p> <pre><code>using System; class MyClass { public virtual void A() { Console.WriteLine("MyClass.A"); } public virtual void B() { Console.WriteLine("MyClass.B"); } } class ClassA : MyClass { public override void A() { Console.WriteLine("AttachmentA.A"); base.A(); } } class ClassB : MyClass { public override void B() { Console.WriteLine("AttachmentB.B"); } } public class Program { public static void Main(string[] Args) { MyClass aaa = new ClassA(); MyClass bbb = new ClassB(); aaa.A(); // prints MyClass.A aaa.B(); // prints MyClass.B (aaa as ClassA).A(); // prints AttachmentA.A (aaa as ClassA).B(); // prints MyClass.B bbb.A(); // prints MyClass.A bbb.B(); // prints MyClass.B (bbb as ClassB).A(); // prints AttachmentB.A + MyClass.A (bbb as ClassB).B(); // prints AttachmentB.B } } </code></pre> <p>Here's another example, similar to what blowdart suggested:</p> <pre><code>interface ICallMe { bool A(); bool B(); } class MyClass { public ICallMe Attachment { get; set; } public void A() { bool BaseFunction = true; if (Attachment != null) BaseFunction = Attachment.A(); if (BaseFunction) Console.WriteLine("MyClass.A"); } public void B() { bool BaseFunction = true; if (Attachment != null) BaseFunction = Attachment.B(); if (BaseFunction) Console.WriteLine("MyClass.B"); } } class ClassA : ICallMe { public bool A() { Console.WriteLine("AttachmentA.A"); return true; } public bool B() { Console.WriteLine("AttachmentA.B"); return false; } } static class Program { static void Main(string[] args) { MyClass aaa = new MyClass(); aaa.A(); // prints MyClass.A aaa.B(); // prints MyClass.B aaa.Attachment = new ClassA(); aaa.A(); // should print AttachmentA.A &lt;newline&gt; MyClass.A aaa.B(); // should print AttachmentB.B } } </code></pre> <p>This only allows for a single attachment to be added. If you wanted to override the behavior of several functions separately, you could use a Collection of some sort to hold the attachments. Within the base class you'd need to loop through them and find the one you want to execute.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload