C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值
一、引入
最近遇到一个项目里面的功能,在给实体类赋值的时候,由于赋值字段是动态生成的,所以如果用常用的方法(直接实体类的名称.字段名=要赋的值),将会生成很多无用的代码,所以找到了一个通过反射的赋值与取值的方法,顺便总结一下,以及对比一下与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 = ,
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.源码
__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。
C#、Python中分别是怎么实现通过字符串获取实体类的值以及给实体类赋值的更多相关文章
- python中的printf:%号拼接字符串和format函数
在C语言中,我们使用printf("%s","hello")这种形式进行字符串的拼接 在python中,进行这样的拼接有两种实现方式,分别是%号拼接以及使用fo ...
- python中的is判断引用的对象是否一致,==判断值是否相等
python中的is判断引用的对象是否一致,==判断值是否相等 a = 10 b = 20 list = [1,2,3,4,5] print(a in list) print(b not in lis ...
- 快速理解Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容的区别
<Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容有何不同?>老猿介绍了二者的区别,为了快速理解,老猿在此使用另外一种方式补充说明一下: 1.使用%r是调用objec ...
- Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容有何不同?
Python中使用百分号占位符的字符串格式化方法中%s和%r表示需要显示的数据对应变量x会以str(x)还是repr(x)输出内容展示. 关于str和repr的关系请见: <Python中rep ...
- Python中使用%还是format来格式化字符串?
Python中应该使用%还是format来格式化字符串? %还是format Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了form ...
- python中subprocess.Popen执行命令并持续获取返回值
先举一个Android查询连接设备的命令来看看Python中subprocess.Popen怎么样的写法.用到的命令为 adb devices. import subprocess order='ad ...
- Python中的列表,元组,字符串之间的相互转化
Python中的列表元组和字符串之间的相互转化需要利用,tuple(),list(),str(). 示例如下: >>> the_string = "hello I'am x ...
- 对于Python中的字节串bytes和字符串以及转义字符的新的认识
事情的起因是之前同学叫我帮他用Python修改一个压缩包的二进制内容用来做fuzz,根据他的要求,把压缩包test.rar以十六进制的方式打开,每次修改其中一个十六进制字符串并保存为一个新的rar用来 ...
- javascript中json对象json数组json字符串互转及取值
今天用到了json数组和json对象和json类型字符串之间互转及取值,记录一下: 1.json类型的字符串转换为json对象及取值 var jsonString = '{"bar" ...
随机推荐
- vue数据更新UI不刷新显示解决方案
vue比较常见的坑就是数据(后台返回)更新了,但是UI界面并没有更新,常见于以下情况: 一.数据为数组时1.通过数组索引修改数组元素例如: 此时UI数据并不会刷新 2.修改数组长度时: 解决方案: 如 ...
- position 小结
position: static fixed relative absolute sticky 1.static static定位是HTML元素的默认值,即没有定位,元素出现在正常的流中.因此,这种定 ...
- Android基础知识学习
IPC (Inter-Process Communication) 意思是: 进程间的通信,是指两个进程之间进行数据交换的过程. Android中如何开启多进程呢? 只需要给四大组件(Activit ...
- R_展示变量之间关系的图形
#绘制普通矩阵散点图 plot(dataframe) #绘制带有拟合直线,最佳拟合曲线和直方图的矩阵散点图 library(car) attach(dataframe) scatterplotMatr ...
- MFC单文档视图程序简介
在视图应用程序中,应用程序的数据由文档对象代表,数据的视图由视图对象代表.MFC的Cdocument类是文档对象的基类,Cview类是视图对象的基类.应用程序的主窗口,其操作功能在MFC的Cframe ...
- unity API 之EventSystem.current.IsPointerOverGameObject()
命名空间 :UnityEngine.EventSystems 官方描述: public bool IsPointerOverGameObject(); public bool IsPointerOve ...
- 安全运维中基线检查的自动化之ansible工具巧用
i春秋作家:yanzm 原文来自:安全运维中基线检查的自动化之ansible工具巧用 前几周斗哥分享了基线检查获取数据的脚本,但是在面对上百台的服务器,每台服务器上都跑一遍脚本那工作量可想而知,而且都 ...
- 吴恩达机器学习笔记5-梯度下降I(Gradient descent intuition)
梯度下降是一个用来求函数最小值的算法,我们将使用梯度下降算法来求出代价函数
- 全栈开发工程师微信小程序-中(中)
全栈开发工程师微信小程序-中(中) 开放能力 open-data 用于展示微信开放的数据 type 开放数据类型 open-gid 当 type="groupName" 时生效, ...
- [Swift]SwiftyJSON的使用:解析JSON
用法 初始化Initialization import SwiftyJSON let json = JSON(data: dataFromNetworking) 或者 let json = JSON( ...