一、引入
最近遇到一個項目里面的功能,在給實體類賦值的時候,由於賦值字段是動態生成的,所以如果用常用的方法(直接實體類的名稱.字段名=要賦的值),將會生成很多無用的代碼,所以找到了一個通過反射的賦值與取值的方法,順便總結一下,以及對比一下與Python語言同樣實現該功能的區別之處。
二、C#
1.賦值
2.取值
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 = 1, 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.截圖
2.源碼

1 __author__ = "JentZhang" 2 3 # 實體類 4 class Student: 5 def __init__(self, id, name, addr): 6 self.id = id 7 self.name = name 8 self.addr = addr 9 10 def main(): 11 stu = Student(1, '張三', '上海市') 12 v_id = 'id' 13 v_name = 'name' 14 v_addr = 'addr' 15 print(hasattr(stu, v_id)) # 是否有該屬性 16 print(hasattr(stu, 'sex')) # 是否有該屬性 17 print('=========================') 18 print(getattr(stu, v_id, 5)) # 獲取屬性值,如果沒有改屬性,則可以設置返回默認值,這里的默認值設置為5 19 print(getattr(stu, v_name, '李四')) # 獲取屬性值,如果沒有改屬性,則可以設置返回默認值,有該屬性 20 print(getattr(stu, 'abc', '李四')) # 獲取屬性值,如果沒有改屬性,則可以設置返回默認值,沒有該屬性 21 print('=========================') 22 setattr(stu, v_id, 1000) #設置屬性對應的值 23 setattr(stu, v_name, '王五') #設置屬性對應的值 24 setattr(stu, v_addr, '北京市') #設置屬性對應的值 25 26 print(stu.id) 27 print(stu.name) 28 print(stu.addr) 29 30 if __name__ == '__main__': 31 main()
四、總結
個人更喜歡Python的處理方式,非常靈活,大愛Python。