[英]How to access properties of the object type 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
object 的屬性。 即)我需要訪問myList
object 中的Name
、 Id
、 Place
、 Pincode
、 Mark
、 Standard
等屬性及其對應的值。
如何實現?
您可以嘗試以下方法。 工作代碼在這里
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};
}
正如我在評論中所寫,通常在同一個集合中保留完全不同的類型是錯誤的。 但是,這並不意味着總是如此,因此假設您有足夠的理由這樣做 - 這是一種選擇。
假設 c# 7 或更高版本,您最好的選擇可能是(ab)使用帶有模式匹配的開關:
foreach(var obj in myList)
{
switch(obj)
{
case A a:
DoSomethingWithA(a);
break;
case B b:
DoSomethingWithB(b);
break;
}
}
這是我用來比較兩個對象的一些代碼。 我不知道這是否是您的情況,但我希望它可以幫助您獲得所需的東西。
protected List<string> GetProperties(List<object> myList)
{
List<string> props = 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);
}
}
}
return props;
}
如果您只是想從 object(屬性值)中獲取值,那就另當別論了。
foreach (objectType obj in mylist)
{
someVariable1 = obj.name;
someVariable2 = obj.Id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.