As we all know, Reflection.Emit is a very powerful tool that can dynamically generate IL code for various assemblies, types, and methods at runtime, almost omnipotent. I thought so too, but after reading someone's blog I found that it was very tricky to do something special with Reflection.Emit. Let's say you haven't seen that person's blog (for the time being ...). ) can try this problem. The following code can be correctly compiled with vbc.exe (of course, the equivalent C # program can also be tested by the C # compiler cannot handle the logic, you refer to VB behavior bar) ...
Class A
Implements B.I
End Class
Class B
Inherits A
Interface I
End Interface
End Class
The logic of the code is this, a implements the interface I, and I is the embedded type of B, and b inherits from a. Very simple. You can use TypeBuilder to generate this logic, right? A friend who is not familiar with Reflection.Emit or has forgotten how to start can refer to the following code first:
Imports System.Reflection
Imports System.Reflection.Emit
Module Program
Sub Main ()
Dim name = New AssemblyName ("test")
Dim dasm = AppDomain.CurrentDomain.DefineDynamicAssembly (name, Assemblybuilderaccess.runandsave)
Dim dmod = dasm. DefineDynamicModule (name. Name, name. Name + ". dll")
Dim TA = Dmod. DefineType ("A", Typeattributes.public Or Typeattributes.class)
Dim TB = Dmod. DefineType ("B", Typeattributes.public Or Typeattributes.class, TA)
Dim TI = Tb.definenestedtype ("I", typeattributes.nestedpublic or Typeattributes.interface or typeattributes.abstract)
Ta.addinterfaceimplementation (TI)
'...
' You need to complete this part of the logic so that Test.dll contains just three types
'...
Dasm. Save (name. Name + ". dll")
End Sub
End Module
Note that the place has not finished, please complete it, to achieve the above mentioned three types and the correct relationship.
(Do not need to translate into C #, basically only need to change the dim to Var and then add a semicolon is C # ...) )
To be honest, I have just learned about the general plan, there is no hands-on experiment, so let's start doing a work together.