If I build a type with a property using TypeBuilder, do I need to use the Builder property?

I want to use TypeBuilder to create a type that matches the interface. This base type will be an object since I do not have an abstraction point.

The corresponding interface has the following property:

public interface IFoo{ int Property{get;} } 

Do I need to create a PropertyBuilder? Or can I just get rid of emitting a method for int get_Property() method?

+4
source share
2 answers

The CLI does not care about properties if all methods (which are really defined by the interface) have the following implementations:

 var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName("foo"), AssemblyBuilderAccess.RunAndSave); var mb = ab.DefineDynamicModule("foo"); var tb = mb.DefineType("bar"); tb.AddInterfaceImplementation(typeof(IFoo)); var method = typeof(IFoo).GetProperty("Property").GetGetMethod(); var impl = tb.DefineMethod("impl", MethodAttributes.Private | MethodAttributes.Virtual, typeof(int), Type.EmptyTypes); var il = impl.GetILGenerator(); il.Emit(OpCodes.Ldc_I4_7); // because it is lucky il.Emit(OpCodes.Ret); tb.DefineMethodOverride(impl, method); var type = tb.CreateType(); IFoo foo = (IFoo)Activator.CreateInstance(type); var val = foo.Property; 
+5
source

I would think that you need to use PropertyBuilder - a property in .Net is not as simple as having get_ and / or set_ methods, additional metadata is needed there.

I never used TypeBuilder, but I would be very surprised if you could leave just by issuing the get_ method.

0
source

All Articles