2009-07-01 20 views
6

que tienen una clase con un valor de propiedad de esta manera:Cómo usar MethodInfo.Invoke para establecer el valor de propiedad?

public class MyClass { 
    public property var Value { get; set; } 
    .... 
} 

Quiero usar MethodInfo.Invoke() para establecer valor de la propiedad. Aquí hay algunos códigos:

object o; 
// use CodeDom to get instance of a dynamically built MyClass to o, codes omitted 
Type type = o.GetType(); 
MethodInfo mi = type.GetProperty("Value"); 
mi.Invoke(o, new object[] {23}); // Set Value to 23? 

no puedo acceder a mi trabajo VS en este momento. Mi pregunta es cómo establecer el valor con un valor entero como 23?

+0

Uso PropertyInfo.SetValue, tal como se menciona a continuación. Si alguna vez encuentra que está obligado a usar un objeto MethodInfo, obtenga el método "get" de la propiedad (PropertyInfo.GetGetMethod()) e inícielo como se indicó anteriormente. –

Respuesta

13

Puede usar el método PropertyInfo.SetValue.

object o; 
//... 
Type type = o.GetType(); 
PropertyInfo pi = type.GetProperty("Value"); 
pi.SetValue(o, 23, null); 
+0

en realidad debería ser: pi.SetValue (o, 23, null); ? no 0 –

+0

Sí, se corrigió el error ... – CMS

2

Si está utilizando .NET Framework 4.6 y 4.5, también se puede utilizar PropertyInfo.SetMethod Property:

object o; 
//... 
Type type = o.GetType(); 
PropertyInfo pi = type.GetProperty("Value"); 
pi.SetMethod.Invoke(o, new object[] {23}); 
Cuestiones relacionadas