2009-04-10 76 views

回答

3

你的意思是Reflection.Emit?如果是這樣,您使用TypeBuilder.DefineMethod,與MethodAttributes.Abstract

下面是一個例子;在Bar.Methodabstract; Bar2.Method覆蓋它。

AssemblyName an = new AssemblyName("Foo"); 
    var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); 
    var module = asm.DefineDynamicModule("Foo"); 
    var type = module.DefineType("Bar", TypeAttributes.Abstract | TypeAttributes.Class | TypeAttributes.AnsiClass); 
    var method = type.DefineMethod("Method", MethodAttributes.Abstract | MethodAttributes.Public | MethodAttributes.Virtual, 
     CallingConventions.HasThis, typeof(int), Type.EmptyTypes); 

    var final = type.CreateType(); 

    type = module.DefineType("Bar2", TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.AnsiClass, final); 
    var method2 = type.DefineMethod("Bar", MethodAttributes.Public | MethodAttributes.Virtual, 
     CallingConventions.HasThis, typeof(int), Type.EmptyTypes); 
    var il = method2.GetILGenerator(); 
    il.Emit(OpCodes.Ldc_I4_4); 
    il.Emit(OpCodes.Ret); 
    type.DefineMethodOverride(method2, method); 

    var concrete = type.CreateType(); 
    object obj = Activator.CreateInstance(concrete); 
    int result = (int) concrete.GetMethod("Bar").Invoke(obj, null); 
+0

啊,是的,這更可能是問題的含義。我會留下我的回答,以防萬一它變得有用,但我認爲你有這個:) – 2009-04-10 19:47:39

0

你的意思是CodeDOM?反射用於讀取現有的代碼,而不是創建新的代碼。

如果意味着CodeDOM的,我相信,你只需要創建CodeMemberProperty並設置其屬性Attributes包括MemberAttributes.Abstract