当前位置:网站首页>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# 反射 判断类型是否是列表》
边栏推荐
- 神经网络分类
- 300万招标!青岛市医疗保障局主机数据库中间件运行维护服务项目
- 轻量级接口自动化框架(jmeter+ant+jenkins)
- MySQL----索引
- E121: Unable to open and write file solution when vim /etc/profile is written
- 2G 3G 4G 5G 基站覆盖范围
- 二、线性结构
- GC explanation and tuning of JVM
- Thoroughly understand the differences and application scenarios of session, cookie, sessionStorage, and localStorage (interview orientation)
- 易周金融分析 | 互联网系小贷平台密集增资;上半年银行理财子公司综合评价指数发布
猜你喜欢
随机推荐
七、图结构
Postman使用简单演示
leetcode-636:函数的独占时间
八、排序与搜索
LeetCode_487_最大连续1的个数Ⅱ
论文阅读《Omnidirectional DSO: Direct Sparse Odometry with Fisheye Cameras》
Mysql的分布式事务原理理解
小程序使用npm包
卫星互联网真能替代 5G?
Combining "xPlus" to discuss the innovation and change of software architecture
产品-Axure9英文版,下拉框Droplist的条件选择,显示不同内容面板
Some optional strategies and usage scenarios for PWA application Service Worker caching
详细讲解修改allure报告自定义的logo和名称中文
基于STM32的简易示波器项目(含代码)——HAL库
JVM的GC讲解及调优
vim /etc/profile 写入时 出现 E121:无法打开并写入文件解决方案
【C语言】[编程题]倒置字符串
转转商品系统高并发实战(数据篇)
NLP和CV中的Local和Global建模
分分钟快速定制您的专属个性化软件应用——BizTool自动化工具简介