2013-03-29 20 views
5

Chcę zaimplementować interfejs, który automatycznie czyści wszystkie pola lokalnych, jak dotąd mam:W jaki sposób wyemitujesz domyślną wartość typu?

// Implement IClearable 
dynamicType.AddInterfaceImplementation(typeof(IClearable)); 

MethodBuilder clearnMethodBuilder = dynamicType.DefineMethod("Clear", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard); 
ILGenerator clearMethodILGen = clearnMethodBuilder.GetILGenerator(); 

foreach (FieldBuilder localField in fields) 
{ 
    clearMethodILGen.Emit(OpCodes.Ldarg_0); 
    clearMethodILGen.Emit(OpCodes.Ldfld, localField); 
    clearMethodILGen.Emit(OpCodes.??, Profit??); 
} 

clearMethodILGen.Emit(OpCodes.Ret); 

Jak ustawić ostatni krok, aby zapisać wartość domyślną na polu?

+1

Jest to interesujące? http://stackoverflow.com/questions/10400358/how-to-translate-defaultsometype- from-c-sharp-to-cil –

+0

Tak, to pomaga. Właściwie to odkrywam, że właściwą metodą może być wysłanie Activator.CreateInstance (T). Ponieważ spowoduje to automatyczne utworzenie instancji domyślnego obiektu. – sircodesalot

+0

klasa lub struktura? Jeśli to drugie, możesz zrobić 'this = new StructName()'. – leppie

Odpowiedz

4

coś takiego:

clearMethodILGen.Emit(OpCodes.Ldfld, localField); 
clearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType); 
Powiązane problemy