C # - Internal properties are readable in quickwatch but don't use reflection?

I see that the "Quick Watch" window has access to all properties, regardless of the access restrictions (internal, protected, closed) of the class in the library, even if the library is referenced in a completely different application, lib and Namespace. While I do not find a way to access them using reflection. I especially try to "read" (note - just read) the internal property of the assembly. If this is not possible by design of how the "internal" (not accessible outside the same namespace) works, how is it "read" in the Quick View window in VS.NET?

Here is an example of the code I used:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestLib { public class TestInteralProp { internal string PropertyInternal { get { return "Internal Property!"; } } protected string PropertyProtected { get { return "Protected Property!"; } } string PropertyPrivate { get { return "Private Property!"; } } public string PropertyPublic { get { return "Public Property!"; } } protected internal string PropertyProtectedInternal { get { return "Protected Internal Property!"; } } } } 

When I create an object for the TestInernalProp class, I can see all 4 properties in quickwatch -

props

And when I use reflection to access any of them except the public property (PropertyPublic), I get an exception with a null reference.

 //this works propTestObj.GetType().InvokeMember("PropertyPublic", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null); //this fails (obviously) propTestObj.GetType().InvokeMember("PropertyInternal", System.Reflection.BindingFlags.GetProperty, null, propTestObj, null); //this works propTestObj.GetType().GetProperty("PropertyPublic").GetValue(propTestObj, null); //this fails again propTestObj.GetType().GetProperty("PropertyInternal").GetValue(propTestObj, null) 

I don’t understand how Quick Watch can access them.

+4
source share
1 answer

Use these flags.

 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance 

The GetProperty flag is not required for this operation. You might want to add Static .

Note. You can combine flags with | , because their integer values ​​have two degrees. See this SO answer .


NOTE (In response to Lalman and shanks comments on Reflection security issues)

There is always a way to write bad or dangerous code. It is up to you to decide whether or not. Reflection is not an ordinary way of doing something, but means that it is intended for programming special tools such as o / r-mappers or analysis tools. The reflection is very strong; however, you must use it wisely.

+12
source

Source: https://habr.com/ru/post/1400989/


All Articles