简体   繁体   中英

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

I'm sure this is simple, but I'm 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 (it could be one of multiple classes, all of which have this variable included, this is why I have to use Reflection). 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...
}

You can simply call a static member with the ClassName.memberName syntax:

string localStr = First.theStringToGet;

If the member is not static, you must have an object created from this class and then use the objectName.memberName syntax:

// Assuming the that `theStringToGet` was not static.
First obj = new First();
string localStr = obj.theStringToGet;

You don't need Reflection for those things.


If the class name changes, this does not work with static members. If you need a static behaviour, you can use the singleton pattern and either derive the classes from the same base class, or let them implement the same interface. I will show the interface variant.

public interface IStringProvider
{
    string TheString { get; }
}

public class First : IStringProvider
{
    public static readonly First Instance = new First();

    private First() {} // Make constructor private, so no one else can instantiate.

    public string TheString => "some text";
}

public class Second : IStringProvider
{
    public static readonly First Instance = new Second();

    private Second() {}

    public string TheString => "another text";
}

Now, you can access the string like this

void AccessTheString(IStringProvider provider)
{
    string localStr = provider.TheString;
}

Example:

AccessTheString(First.Instance);
AccessTheString(Second.Instance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM