c# - 如何访问对象类型c#的属性?
问题描述
var obj1 = new A()
{
Name = "abc",
Id = 1
}
var obj2 = new B()
{
Place = "XYZ",
Pincode = 123456
}
var obj3 = new C()
{
Mark = 100,
Standard = "Tenth"
}
var myList = new List<object>();
myList .add(obj1);
myList .add(obj2);
myList .add(obj3);
这是我的代码结构。我需要访问myList
对象的属性。即)我需要从对象访问属性,如Name
, Id
, Place
, Pincode
, Mark
,它的相应值。Standard
myList
如何实现?
解决方案
您可以尝试以下方法。工作代码在这里
public static List<List<string>> GetProperties(List<object> myList)
{
// If you don't want two lists, you can use Dictionary<key, value>
List<string> props = new List<string>();
List<string> values = new List<string>();
foreach (var a in myList)
{
if(a == null)
continue;
var propsInfo = a.GetType().GetProperties();
foreach (var prop in propsInfo)
{
if(!props.Contains(prop.Name))
{
props.Add(prop.Name);
values.Add(prop.GetValue(a, null).ToString());
}
}
}
return new List<List<string>> { props, values};
}
推荐阅读
- javascript - .map 不是 javascript 中的函数
- excel - Angular如何使用typeScript从资产文件夹中读取excel文件
- php - 如何将 HTML 上传表单转换为 PHP/cURL 函数
- authentication - 实现 OpenID 以及您自己的身份验证
- c# - 根据其数据库表列值在 Silverlight 网站中显示值
- javascript - 屏蔽输入错误地获取数据
- visual-c++ - SendMessage WM_COPYDATA msg 从 VC 到 BCB:失败,但 BCB 到 BCB:通过
- python - 如何在 Python 中引用一个目录以便它在多台计算机上工作?
- javascript - 如何使用 electron.js 在一个窗口中呈现两个 html 页面
- excel - 动态填充另一个表循环