How to get a class of an internal static class in another assembly?

I have a class C in Assembly A, like this:

internal class C { internal static string About_Name { get { return "text"; } ... } 

I have about 20 of these static properties. Is there a way, in an external assembly, without using the assembly attribute of the node (only to reflect .Net only), to get class C so that I can refer to any of the properties of the static string as follows:

 Class C = <some .Net reflection code>; string expected = C.About_Name; 

If this is not possible, the .Net reflection code to get the value of the string property directly will be sufficient, but not ideal.

+4
source share
2 answers

Try it...
Edit: I did not think of simply using this type instead of an object instance when it was a static property.
Removed var obj = Activator.CreateInstance(type); and use type in prop.GetValue instead of obj .

 namespace ClassLibrary1 { internal class Class1 { internal static string Test { get { return "test"; } } } public class Class2 { } } var ass = Assembly.GetAssembly(typeof(Class2)); var type = ass.GetType("ClassLibrary1.Class1"); var prop = type.GetProperty("Test", BindingFlags.Static | BindingFlags.NonPublic); var s = (string)prop.GetValue(type, null); 
+5
source

Yes, it can be done.

Used by Type.GetProperty() .

Example:

 // Load your assembly and Get the Type // Assembly load code... ... // Get type Type asmType = typeof(C); // Get internal properties PropertyInfo pi = asmType.GetProperty("About_Name", BindingFlags.NonPublic | BindingFlags.Static); // Get Value var val = pi.GetValue(asmType, null); 

This code will return " text " to val , so from there do what you need with it.

To do this in the sense in which you want, enter the code into the method as follows:

  private static string GetString(Type classToCheck, string PropertyName) { PropertyInfo pi = classToCheck.GetProperty(PropertyName, BindingFlags.NonPublic | BindingFlags.Static); object val = null; if (pi != null) val = pi.GetValue(classToCheck, null); return (val != null) ? val.ToString() : string.Empty; } 

Then use will be:

 string expected = GetString(typeof(C), "About_Name"); 
0
source

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


All Articles