2010-09-21 82 views

回答

89

檢查你從GetSetMethod回來:

MethodInfo setMethod = propInfo.GetSetMethod(); 

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

或者,換一個不同的自旋Richard's answer

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

注如果你想要做的只是設置一個屬性,只要它有一個setter,你就不會實現你必須關心二傳手是否公開。你可以使用它,公共私人:

// 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:這比GetSetMethod()更好。IsPublic' :它也適用於屬性有* no * setter的情況。 – Ani 2010-09-21 16:42:10

+0

謝謝@Dan Tao。這是最好的答案:upvoted! – 2010-09-21 16:53:48

+0

謝謝@丹濤。 :) – 2012-07-17 06:32:52

9

.NET屬性實際上是get和set方法的一個包裝外殼。

您可以在PropertyInfo上使用GetSetMethod方法,返回引用setter的MethodInfo。你可以用GetGetMethod做同樣的事情。

如果getter/setter是非公開的,這些方法將返回null。這裏

正確的代碼是:

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

您需要使用的下屬方法來確定可訪問性,使用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; 

但是請注意,吸氣劑&制定者可能有不同的通達性,例如:

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

所以你不能假設的getter和二傳手將具有相同的知名度。