在 C# 中使用变量值的引用访问访问修饰符

Access access modifier with reference of variable value in c#

我通过字符串

访问了另一个class的访问修饰符变量

使用变量值的引用访问另一个 class 的访问修饰符字符串变量。 在代码中,简单的字符串变量是访问,但对于访问修饰符变量,它给出了异常。 我怎样才能访问它。

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);

它也是 returns PropertyInfo 实例而不是 FieldInfo,但它具有相同的 GetValue 方法。