C# 通过字符串访问类属性值 - 不使用反射
在C#中,您可以使用switch语句来访问类内的一个指定属性的值,而不使用反射。以下是一个示例:\n\ncsharp\npublic class MyClass\n{\n public string Property1 { get; set; }\n public string Property2 { get; set; }\n}\n\npublic static class ClassHelper\n{\n public static string GetPropertyValue(MyClass obj, string propertyName)\n {\n switch (propertyName)\n {\n case "Property1":\n return obj.Property1;\n case "Property2":\n return obj.Property2;\n default:\n throw new ArgumentException("Invalid property name");\n }\n }\n}\n\npublic static void Main(string[] args)\n{\n MyClass myObj = new MyClass\n {\n Property1 = "Value1",\n Property2 = "Value2"\n };\n\n string propertyValue = ClassHelper.GetPropertyValue(myObj, "Property1");\n Console.WriteLine(propertyValue); // Output: Value1\n}\n\n\n在上述示例中,ClassHelper类包含一个静态方法GetPropertyValue,该方法接受一个MyClass对象和一个属性名作为参数,并使用switch语句根据属性名返回相应属性的值。在Main方法中,我们创建了一个MyClass对象,并通过调用ClassHelper.GetPropertyValue方法来获取Property1属性的值。最后,我们将属性值打印到控制台上。
原文地址: https://www.cveoy.top/t/topic/pV61 著作权归作者所有。请勿转载和采集!