c#中带有变量值引用的访问修饰符
本文关键字:访问 引用 变量值 | 更新日期: 2023-09-27 18:07:06
我通过字符串
访问另一个类的访问修饰符变量go to access modifier使用变量value引用其他类的String变量。在代码中,简单的字符串变量是访问,但对于访问修饰符变量,它给出异常。如何访问
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyReflectionClass c = new MyReflectionClass();
var t = c.GetType().GetField("str1").GetValue(c);
Console.WriteLine(t);
var test = c.GetType().GetField("str").GetValue(c);
Console.WriteLine(test);
Console.ReadKey();
}
public class MyReflectionClass
{
public string str { get { return "String with access modifier "; } }
public string str1 = "string variable";
}
}
}
输出:字符串变量
str1
不是一个字段,而是一个属性。因此,您需要使用GetProperty
方法。
var test = c.GetType(). GetProperty("str") .GetValue(c);
它也返回PropertyInfo
实例而不是FieldInfo
,但它具有相同的GetValue
方法。