Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add interfaces to a class programmatically (at runtime)
    primarykey
    data
    text
    <p>I am looking for a way to add an interface implementation to a class at runtime. Here is a sample code, which I will discuss below.</p> <pre><code>Public Interface IAction Sub DoThis(a As Integer) End Interface Class Actor Implements IAction Private mNumber As Integer Public Sub New(number As Integer) mNumber = number End Sub Public Sub DoThis(a As Integer) Implements IAction.DoThis Console.WriteLine(String.Format("Actor #{0}: {1}", mNumber, a)) End Sub End Class Class ActionDispatcher Implements IAction Private Shared mActionList As New List(Of IAction) Public Shared Sub Add(actor As IAction) mActionList.Add(actor) End Sub Public Sub DoThis(a As Integer) Implements IAction.DoThis For Each act In mActionList act.DoThis(a) Next End Sub End Class Module Module1 Sub Main() Dim a As New ActionDispatcher ActionDispatcher.Add(New Actor(1)) ActionDispatcher.Add(New Actor(2)) a.DoThis(5) End Sub End Module </code></pre> <p>This is related to WCF, where one needs to provide to CreateHost a single class, which implements all interfaces required for the end points. In this scenario, ActionDispatcher is such a class, and IAction is one of the many interfaces to be implemented.</p> <p>My vision is to avoid implementing IAction in ActionDispatcher manually, but have some sort of registration mechanism, where I can say, that ActionDispatcher must implement interfaces IAction, IDoing, INoAction, etc - and have the dispatching methods generated for me.</p> <p>MSDN says, that any class is compatible with any interface, so I don't need to declare "Implements" in the ActionDispatcher. But I still need to implement the interface and connect the implementing method to the interface definition, so WCF can find it when needed.</p> <p>The closest thing I found is probably the <a href="http://www.codeproject.com/Articles/22832/Automatic-Interface-Implementer-An-Example-of-Runt" rel="nofollow">Automatic Interface Implementer</a>, but it (1) creates a new type, (2) adds dummy methods.</p> <p>I has also tried to understand CodeCompileUnit class, but so far couldn't see the relation to what I need.</p> <p>Can someone more experienced in Reflection API help me out? Is there a nice way to do whay I want?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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