2010-09-21 7 views

उत्तर

89

चेक क्या आप GetSetMethod से वापस पाने:

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

नोट:

MethodInfo setMethod = propInfo.GetSetMethod(); 

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

या, Richard's answer पर एक अलग स्पिन डाल करने के लिए कि अगर आप ऐसा करना चाहते हैं, तब तक एक संपत्ति सेट करें जब तक कि उसके पास एक सेटटर हो, आप कार्य नहीं करते हैं वाई परवाह है कि सेटटर सार्वजनिक है या नहीं। तुम बस के लिए इसका इस्तेमाल कर सकते हैं, सार्वजनिक या निजी:

// 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' : यह तब भी काम करता है जब संपत्ति में * नहीं * सेटर होता है। – Ani

+0

धन्यवाद @ दैन ताओ। यह सबसे अच्छा जवाब है: ऊपर उठाया! –

+0

धन्यवाद @ दैन ताओ। :) –

9

.NET गुण वास्तव में एक प्राप्त और सेट विधि के चारों ओर एक रैपिंग खोल हैं।

आप प्रॉपर्टीइन्फो पर GetSetMethod विधि का उपयोग कर सकते हैं, जो Setter को संदर्भित MethodInfo लौटा रहा है। आप GetGetMethod के साथ एक ही काम कर सकते हैं।

गेटटर/सेटर गैर-सार्वजनिक होने पर ये विधियां शून्य हो जाएंगी।

सही कोड यहाँ है:

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; 

हालांकि, ध्यान दें गेटर & सेटर अलग accessibilities हो सकता है, उदा .:

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

तो तुम कल्पना नहीं कर सकते कि गेटर और सेटर ही दृश्यता होगा।

संबंधित मुद्दे

 संबंधित मुद्दे