How to check if a network resource is open

For a PropertyInfo object, how can I verify that the property setting tool is public?

+43
reflection c #
Sep 21 '10 at 16:36
source share
4 answers

Check that you will return from GetSetMethod :

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

Or, to respond differently to Richard's answer :

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

Note that if all you want to do is set the property while it has a setter, you actually do not need to worry about whether the setter is publicly available. You can simply use it, public or private:

 // 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 }); } 
+86
Sep 21 '10 at 16:39
source share

.NET properties are really a wrapper around the get and set method.

You can use the GetSetMethod method in PropertyInfo by returning MethodInfo referring to the installer. You can do the same with GetGetMethod .

These methods return null if the getter / setter is not public.

The correct code is here:

 bool IsPublic = propertyInfo.GetSetMethod() != null; 
+9
Sep 21 '10 at 16:38
source share
 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 a setter Console.WriteLine(setter.IsPublic); } } } } 
+4
Sep 21 '10 at 16:39
source share

To determine accessibility, you need to use the underling method using PropertyInfo.GetGetMethod () or 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; 

Please note, however, that getters and setters may have different capabilities, for example:

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

Therefore, you cannot assume that the receiver and setter will have the same visibility.

0
Sep 21 '10 at 16:40
source share



All Articles