2010-09-21 9 views

Respuesta

89

Comprobar lo que se obtiene de vuelta de GetSetMethod:

MethodInfo setMethod = propInfo.GetSetMethod(); 

if (setMethod == null) 
{ 
    // The setter doesn't exist or isn't public. 
} 

O, para decirlo de un giro diferente en Richard's answer:

if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic) 
{ 
    // The setter exists and is public. 
} 

Nota que si todo lo que quieres hacer es establecer una propiedad siempre que tenga un setter, no realizas y tiene que importarle si el colocador es público. Que sólo puede usarlo, pública o privada:

// This will give you the setter, whatever its accessibility, 
// assuming it exists. 
MethodInfo setter = propInfo.GetSetMethod(/*nonPublic*/ true); 

if (setter != null) 
{ 
    // Just be aware that you're kind of being sneaky here. 
    setter.Invoke(target, new object[] { value }); 
} 
+0

+1: Esto es mejor que 'GetSetMethod(). IsPublic' : también funciona cuando la propiedad tiene * no * setter. – Ani

+0

Gracias @Dan Tao. Esta es la mejor respuesta: ¡votado! –

+0

Gracias @Dan Tao. :) –

9

. Las propiedades .NET son realmente una envoltura alrededor de un método get y set.

Puede utilizar el método GetSetMethod en PropertyInfo, devolviendo la MethodInfo referente al setter. Puede hacer lo mismo con GetGetMethod.

Estos métodos devolverán nulo si el getter/setter no es público.

El código correcto en este caso es:

bool IsPublic = propertyInfo.GetSetMethod() != null; 
4
public class Program 
{ 
    class Foo 
    { 
     public string Bar { get; private set; } 
    } 

    static void Main(string[] args) 
    { 
     var prop = typeof(Foo).GetProperty("Bar"); 
     if (prop != null) 
     { 
      // The property exists 
      var setter = prop.GetSetMethod(true); 
      if (setter != null) 
      { 
       // There's a setter 
       Console.WriteLine(setter.IsPublic); 
      } 
     } 
    } 
} 
0

Es necesario utilizar el método subordinado para determinar la accesibilidad, el uso o PropertyInfo.GetGetMethod()PropertyInfo.GetSetMethod().

// Get a PropertyInfo instance... 
var info = typeof(string).GetProperty ("Length"); 

// Then use the get method or the set method to determine accessibility 
var isPublic = (info.GetGetMethod(true) ?? info.GetSetMethod(true)).IsPublic; 

Nótese, sin embargo, que el colocador captador & puede tener diferentes accesibilidades, por ejemplo .:

class Demo { 
    public string Foo {/* public/* get; protected set; } 
} 

Así que no se puede asumir que el comprador y el colocador tendrán la misma visibilidad.

Cuestiones relacionadas