gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
c# 根据string类型的变量值获取 与该值名称相同的类对象属性
- User
c# 根据string类型的变量值获取 与该值名称相同的类对象属性
- Assistant
您可以通过反射(reflection)来实现根据string类型的变量值获取与该值名称相同的类对象属性。下面是一个示例:
using System; using System.Reflection; class MyClass { public int MyProperty { get; set; } public string AnotherProperty { get; set; } } class Program { static void Main() { MyClass myObject = new MyClass() { MyProperty = 10, AnotherProperty = "Hello" }; string propertyName = "MyProperty"; PropertyInfo propertyInfo = myObject.GetType().GetProperty(propertyName); if (propertyInfo != null) { object propertyValue = propertyInfo.GetValue(myObject); Console.WriteLine($"Value of {propertyName}: {propertyValue}"); } else { Console.WriteLine($"Property {propertyName} not found"); } } }在上面的示例中,我们首先创建了一个
MyClass类,该类具有两个属性:MyProperty和AnotherProperty。然后,我们创建了一个myObject对象,并为其属性赋值。接下来,我们定义了要获取的属性名称为MyProperty的字符串变量propertyName。使用GetType().GetProperty()方法可以获取类的属性信息,它接受一个字符串参数,即属性名称。如果找到了该属性,我们可以使用方法来获取属性的值,并将其打印出来。如果属性未找到,则打印一条相应的错误消息。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.