gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
c# 根据string类型的变量值获取 与该值名称相同的类对象属性,并给类对象属性赋值
- User
c# 根据string类型的变量值获取 与该值名称相同的类对象属性,并给类对象属性赋值
- Assistant
要根据string类型的变量值获取与该值名称相同的类对象属性,并给类对象属性赋值,可以使用反射来实现。
假设有如下的类对象:
public class MyClass { public string Name { get; set; } public int Age { get; set; } public bool IsStudent { get; set; } }以下是一个示例方法,它根据string类型的变量值获取与该值名称相同的类对象属性,并给类对象属性赋值:
public static void SetValueToProperty<T>(T obj, string propertyName, object propertyValue) { // 获取类对象的类型 Type type = typeof(T); // 获取类对象的属性信息 PropertyInfo property = type.GetProperty(propertyName); // 使用反射给属性赋值 property.SetValue(obj, propertyValue); }你可以调用这个方法,如下所示:
string propertyName = "Name"; string propertyValue = "John"; MyClass myClass = new MyClass(); SetValueToProperty(myClass, propertyName, propertyValue); Console.WriteLine(myClass.Name);输出结果将会是 "John",说明属性Name已经被成功赋值。
请注意,这个方法假设类对象的属性都是可写的。如果属性是只读的,则会抛出异常。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.