当前位置:网站首页>C# 反射 操作列表类型属性
C# 反射 操作列表类型属性
2022-08-08 11:31:00 【yanjinhua】
C# 反射 操作列表类型属性
本文经原作者授权以原创方式二次分享,欢迎转载、分享。
原文作者:唐宋元明清
原文地址: https://www.cnblogs.com/kybs0/p/15112008.html
本文介绍对列表进行创建及赋值的反射操作
我们现在有TestA、TestB类,TestA中有TestB类型列表的属性List,如下:
public class TestA
{
public List<TestB> List { get; set; }
}
public class TestB
{
public TestB(string name)
{
Name = name;
}
public string Name { get; }
}
下面通过反射,给 TestA.List进行赋值, output的期望是 “1,2”;
var testA = new TestA();
var list = new List<TestB>() { new TestB("1"), new TestB("2") };
AddValueToListProperty(testA, nameof(TestA.List), list);
var output = string.Join(",", testA.List.Select(i => i.Name));
1)确定列表及泛型时,可以直接设置属性值;
private void AddValueToListProperty(object objectValue, string propertyName, List<TestB> list)
{
var propertyInfo = objectValue.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objectValue, list, null);
}
2)确定属性是列表,但不确定列表的泛型时,通过列表的Add方式进行设置值;
List<object> list
上方的方案1,是无法进行赋值的,因为类型不一样。会提示隐示转换异常。
private void AddValueToListProperty(object objectValue, string propertyName, List<object> list)
{
var propertyInfo = objectValue.GetType().GetProperty(propertyName);
var newList = Activator.CreateInstance(typeof(List<>).MakeGenericType(propertyInfo.PropertyType.GenericTypeArguments));
propertyInfo.SetValue(objectValue, newList, null);
var addMethod = newList.GetType().GetMethod("Add");
foreach (var item in list)
{
addMethod.Invoke(newList, new object[] { item });
}
}
如上,我们需要先创建一个空列表,对属性进行初始化。propertyInfo.PropertyType.GenericTypeArguments是列表的泛型类型;
然后,获取列表的新增方法 newList.GetType().GetMethod("Add")
,将List<object> list
一项项添加到列表中。
3)不确定属性是否列表,也不确定列表的泛型,可以如下处理;
private void AddValueToListProperty(object objectValue, string propertyName, object list)
{
var propertyInfo = objectValue.GetType().GetProperty(propertyName);
if (typeof(System.Collections.IList).IsAssignableFrom(propertyInfo.PropertyType))
{
var newList = Activator.CreateInstance(typeof(List<>).MakeGenericType(propertyInfo.PropertyType.GenericTypeArguments));
propertyInfo.SetValue(objectValue, newList, null);
var addMethod = newList.GetType().GetMethod("Add");
foreach (var item in (IEnumerable)list)
{
addMethod.Invoke(newList, new object[] { item });
}
}
else
{
propertyInfo.SetValue(objectValue, list, null);
}
}
如果AddValueToListProperty*方法是设置属性值的通用方法,一般可以按上面的方式进行处理。
当然上面的一些代码是简化后的处理,比如判断是否列表,还需要更严谨的判断见《C# 反射 判断类型是否是列表》
边栏推荐
猜你喜欢
Combining "xPlus" to discuss the innovation and change of software architecture
Postman使用简单演示
【kali-权限提升】(4.2.4)社会工程学工具包:远控木马使用、设置、利用
基于ftp协议的上传与下载
office安装出现了“office对安装源的访问被拒绝30068-4(5)”错误
(kali - elevated privileges 】 【 4.2.4) social engineering toolkit: remote control trojans use, set up and use
day01 -Web API介绍—DOM 介绍—获取元素—事件基础—操作元素—排他操作—自定义属性操作—节点操作—案例:动态生成表格—创建元素的三种方式(经典面试题)
关于那些我们都听过的营销工具—优惠券
带你深入理解3.4.2的版本更新,对用户带来了什么?
【访谈】Eotalk Vol.01:Eoapi,我们希望以开源的方式构建 API 生态系统
随机推荐
探究!一个数据包在网络中的心路历程
E121: Unable to open and write file solution when vim /etc/profile is written
3D激光SLAM:LIO-SAM整体介绍与安装编译
目标检测中的Bounding Box Regression Loss
报错 | RegExp2 is not defined
Alibaba微服务组件Nacos注册中心
LeetCode_487_最大连续1的个数Ⅱ
贵州酒店集团特产券解析
Some optional strategies and usage scenarios for PWA application Service Worker caching
Oracle ASM磁盘组使用新存储替换旧存储方案
Thoroughly understand the differences and application scenarios of session, cookie, sessionStorage, and localStorage (interview orientation)
ssh 安全 之 密钥登录
皕杰报表之数据校验与处理
d切片示例
易周金融分析 | 互联网系小贷平台密集增资;上半年银行理财子公司综合评价指数发布
Replication监控及自动故障切换
我用开天平台做了一个城市防疫政策查询系统【开天aPaaS大作战】
部署spark2.2集群(standalone模式)
学习与尝试 --&gt; 事件风暴
ReentrantReadWriteLock读写锁和票据锁StempedLock