dimanche 5 janvier 2020

C# How to get the value of a variable in another class using Reflection

I'm sure this is simple, but Im struggling... all I want to do is read a string variable stored in another class, but using a string as the reference to point to that other class. Using Reflection I have been able to invoke a method in another class, so this does not seem so different... but so far I've had no luck getting this to work. I'd appreciate any pointers (no pun intended!).

Class First
{
   public static string theStringToGet = "some text";
}

//-----------------------------------------------------------------------------------------------------------------

Class Second
{
   String classRef = "Namespace.First";
   String localStr = ??? // I think something like: Type.GetType(classRef).GetField("theStringToGet").GetValue();

   // get value of 'theStringToGet' from 'First' class public var and store in 'localStr' in 'Second' class...
}




Aucun commentaire:

Enregistrer un commentaire