C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值

时间:2023-03-09 08:31:59
C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值

一、引入

  最近遇到一个项目里面的功能,在给实体类赋值的时候,由于赋值字段是动态生成的,所以如果用常用的方法(直接实体类的名称.字段名=要赋的值),将会生成很多无用的代码,所以找到了一个通过反射的赋值与取值的方法,顺便总结一下,以及对比一下与Python语言同样实现该功能的区别之处。

二、C#

  1.赋值

  C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值

  2.取值

  C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值

  3.源码

  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
#region 通过字符串设置实体类的值
//初始化一个实体类
//Student model_stu = new Student();
//string id_str = "stu_id";
//string name_str = "stu_name";
//string addr_str = "stu_address";
//Type type = model_stu.GetType();//获取类型
//PropertyInfo property_info_id = type.GetProperty(id_str);
//PropertyInfo property_info_name = type.GetProperty(name_str);
//PropertyInfo property_info_addr = type.GetProperty(addr_str); //property_info_id.SetValue(model_stu, 5);
//property_info_name.SetValue(model_stu, "李四");
//property_info_addr.SetValue(model_stu, "北京市"); //Console.WriteLine(model_stu.stu_id);
//Console.WriteLine(model_stu.stu_name);
//Console.WriteLine(model_stu.stu_address);
//Console.ReadKey();
#endregion #region 通过字符串获取实体类的值
//初始化一个实体类
Student model_stu = new Student()
{
stu_id = ,
stu_name = "张三",
stu_address = "上海市"
};
string id_str = "stu_id";
string name_str = "stu_name";
string addr_str = "stu_address";
Type type = model_stu.GetType();//获取类型
PropertyInfo property_info_id = type.GetProperty(id_str);
PropertyInfo property_info_name = type.GetProperty(name_str);
PropertyInfo property_info_addr = type.GetProperty(addr_str); Console.WriteLine(property_info_id.GetValue(model_stu));
Console.WriteLine(property_info_name.GetValue(model_stu));
Console.WriteLine(property_info_addr.GetValue(model_stu));
Console.ReadKey();
#endregion }
}
public class Student
{
public int stu_id { get; set; }
public string stu_name { get; set; }
public string stu_address { get; set; }
}
}

三、Python

  1.截图

C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值  

2.源码

  
 __author__ = "JentZhang"

 # 实体类
class Student:
def __init__(self, id, name, addr):
self.id = id
self.name = name
self.addr = addr def main():
stu = Student(1, '张三', '上海市')
v_id = 'id'
v_name = 'name'
v_addr = 'addr'
print(hasattr(stu, v_id)) # 是否有该属性
print(hasattr(stu, 'sex')) # 是否有该属性
print('=========================')
print(getattr(stu, v_id, 5)) # 获取属性值,如果没有改属性,则可以设置返回默认值,这里的默认值设置为5
print(getattr(stu, v_name, '李四')) # 获取属性值,如果没有改属性,则可以设置返回默认值,有该属性
print(getattr(stu, 'abc', '李四')) # 获取属性值,如果没有改属性,则可以设置返回默认值,没有该属性
print('=========================')
setattr(stu, v_id, 1000) #设置属性对应的值
setattr(stu, v_name, '王五') #设置属性对应的值
setattr(stu, v_addr, '北京市') #设置属性对应的值 print(stu.id)
print(stu.name)
print(stu.addr) if __name__ == '__main__':
main()

四、总结

  个人更喜欢Python的处理方式,非常灵活,大爱Python。