Dynamically inherit from inner class through reflection

Is there a way to inherit from an internal abstract class to a dynamically created execution class (e.g. via reflection) using the .NET Framework 4.0?

+5
source share
3 answers

Out of a general sense of perversity in the face of things that should not be possible, I made it clear how far I will try to create a class inherited from System.CurrentSystemTimeZone(inner class in mscorlib). This allows you to refine TypeBuilder, but when you call CreateTypeit, it displays a message TypeLoadExceptionwith the message "Access is denied:" System.CurrentSystemTimeZone "."

A bit more messing around, as it led me to the conclusion that you could create an assembly dynamically that had a strong name that identified it as a friend assembly of the assembly that defines the internal type. But then, in that case, you could just code class Foo : CurrentSystemTimeZonein any case, without a trace.

, , , , , - - :

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;

namespace ReflectPerversely
{
    class SuicidallyWrong
    {
        private static ModuleBuilder mb;
        public static Assembly ResolveEvent(Object sender, ResolveEventArgs args)
        {
            return mb.Assembly;
        }
        public static void Main(string[] args)
        {
            Assembly sys = Assembly.GetAssembly(typeof(string));
            Type ic = sys.GetType("System.CurrentSystemTimeZone",true);
            AssemblyName an = new AssemblyName();
            an.Name = "CheatingInternal";
            AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
            mb = ab.DefineDynamicModule("Mod", "CheatingInternal.dll");
            AppDomain currentDom = Thread.GetDomain();
            currentDom.TypeResolve += ResolveEvent;

            TypeBuilder tb = mb.DefineType("Cheat", TypeAttributes.NotPublic | TypeAttributes.Class, ic);

            Type cheatType = tb.CreateType();
        }
    }
}
+18

. , , Assembly.GetType(), . , , , , , .

+1
source

All Articles