Can anyone tell me how I would create a MustOverride
property using Reflection?
views:
130answers:
2
A:
Do you mean CodeDOM? Reflection is used to read existing code, not create new code.
If you do mean CodeDOM, I believe you just need to create the CodeMemberProperty
and set its Attributes
property to include MemberAttributes.Abstract
.
Jon Skeet
2009-04-10 19:42:19
+3
A:
Do you mean with Reflection.Emit
? If so, you use TypeBuilder.DefineMethod
, with MethodAttributes.Abstract
.
Here's an example; in Bar.Method
is abstract
; Bar2.Method
overrides it.
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);
Marc Gravell
2009-04-10 19:45:48
Ah yes, that's more likely to be the meaning of the question. I'll leave my answer around just in case it turns out to be useful, but I think you've got this one :)
Jon Skeet
2009-04-10 19:47:39