How can you inherit from a sealed class using reflection in .Net?

后端 未结 5 2035
青春惊慌失措
青春惊慌失措 2021-01-07 18:19

Before you start firing at me, I\'m NOT looking to do this, but someone in another post said it was possible. How is it possible? I\'ve never heard of inheriting from anythi

5条回答
  •  借酒劲吻你
    2021-01-07 19:11

    I'm sorry for posting incorrect assumptions in the other thread, I failed to recall correctly. Using the following example, using Reflection.Emit, shows how to derive from another class, but it fails at runtime throwing an TypeLoadException.

    sealed class Sealed
    {
       public int x;
       public int y;
    }
    
    class Program
    {
       static void Main(string[] args)
       {
          AppDomain ad = Thread.GetDomain();
          AssemblyName an = new AssemblyName();
          an.Name = "MyAssembly";
          AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
          ModuleBuilder mb = ab.DefineDynamicModule("MyModule");
          TypeBuilder tb = mb.DefineType("MyType", TypeAttributes.Class, typeof(Sealed));
    
          // Following throws TypeLoadException: Could not load type 'MyType' from
          // assembly 'MyAssembly' because the parent type is sealed.
          Type t = tb.CreateType();
       }
    }
    

提交回复
热议问题