2010-09-21 30 views

Trả lời

89

Kiểm tra những gì bạn nhận lại từ GetSetMethod:

MethodInfo setMethod = propInfo.GetSetMethod(); 

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

Hoặc, để đặt một spin khác nhau trên Richard's answer:

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

Note rằng nếu tất cả những gì bạn muốn làm là thiết lập một thuộc tính miễn là nó có một setter, bạn không actuall y phải quan tâm liệu setter có công khai hay không. Bạn chỉ có thể sử dụng nó, công hoặc tin:

// 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: Điều này tốt hơn 'GetSetMethod(). IsPublic' : nó cũng hoạt động khi thuộc tính có * không * setter. – Ani

+0

Cảm ơn @Dan Tao. Đây là câu trả lời hay nhất: upvoted! –

+0

Cảm ơn @Dan Tao. :) –

9

Thuộc tính .NET thực sự là trình bao gói xung quanh phương thức get và set.

Bạn có thể sử dụng phương thức GetSetMethod trên PropertyInfo, trả về MethodInfo đề cập đến setter. Bạn có thể làm điều tương tự với GetGetMethod.

Các phương thức này sẽ trả về giá trị rỗng nếu trình lấy/đặt không công khai.

Mã đúng ở đây là:

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

Bạn cần phải sử dụng phương pháp hạ để xác định khả năng tiếp cận, sử dụng PropertyInfo.GetGetMethod() hoặc 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; 

Lưu ý, tuy nhiên, các getter & setter có Accessibility khác nhau, ví dụ .:

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

Vì vậy, bạn không thể giả định rằng phương thức getter và setter sẽ có khả năng hiển thị tương tự.

Các vấn đề liên quan