[英]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:您可以使用
ClassName.memberName
语法简单地调用静态成员:
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:如果成员不是静态的,则必须从此类创建一个对象,然后使用
objectName.memberName
语法:
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.