在 C# 中,可以使用反射来访问类内的指定属性的值。下面是一个示例代码:\n\ncsharp\nusing System;\nusing System.Reflection;\n\npublic class MyClass\n{\n public string MyProperty { get; set; }\n}\n\npublic class Program\n{\n public static void Main(string[] args)\n {\n MyClass myObject = new MyClass();\n myObject.MyProperty = \"Hello World\";\n\n string propertyName = \"MyProperty\";\n PropertyInfo propertyInfo = myObject.GetType().GetProperty(propertyName);\n if (propertyInfo != null)\n {\n object propertyValue = propertyInfo.GetValue(myObject);\n Console.WriteLine(propertyValue);\n }\n else\n {\n Console.WriteLine(\"Property not found\");\n }\n }\n}\n\n\n在上面的示例中,我们首先创建了一个 MyClass 类,并定义了一个名为 MyProperty 的属性。然后,在 Main 方法中,我们通过字符串变量 propertyName 指定要访问的属性名。接下来,我们使用反射来获取指定属性的 PropertyInfo 对象。如果找到了对应的属性,我们使用 GetValue 方法来获取属性的值,并将其打印到控制台上。如果未找到属性,则输出 "Property not found"。


原文地址: https://www.cveoy.top/t/topic/pV65 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录