[英]How to extract the data from dictionary Values in c#
您可以使用GetProperties :
PropertyInfo[] myPropertyInfo;
// Get the properties of 'Type' class object.
myPropertyInfo = value.GetType().GetProperties();
Console.WriteLine("Properties of System.Type are:");
for (int i = 0; i < myPropertyInfo.Length; i++)
{
Console.WriteLine(myPropertyInfo[i].ToString());
}
我會提到提出這個問題的人試圖從屬性中獲取值,因此可以通過這種方式完成:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoVerF1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, Car> dictionarySet = new Dictionary<string, Car>();
dictionarySet.Add("Audi", new Car { maxSpeed = 220 });
dictionarySet.Add("BMW", new Car { maxSpeed = 235 });
dictionarySet.Add("Ferrari", new Car { maxSpeed = 285 });
var dataFromReflectionKeys = (dictionarySet.Keys as IEnumerable<string>)?.ToList();
foreach (string keyDic in dataFromReflectionKeys)
{
Console.WriteLine($"For auto {keyDic} type info :");
var dictElem = (dictionarySet[keyDic] as Car);
if (dictElem != null)
{
var propeties = dictElem.GetType().GetProperties();
foreach (var prop in propeties)
{
Console.WriteLine($"Value of property{prop.Name} is {prop.GetValue(dictElem)}");
}
var fields = dictElem.GetType().GetFields();
var methods = dictElem.GetType().GetMethods();
};
}
}
}
}
您在字典的值部分中有一個object
類型。 您可以將object
向下轉換為您的SpecificType
,以便能夠直接訪問 object 屬性。 所以:
using System.Linq;
var query = from obj in dictionary.Values
select obj as SpecificType;
foreach (var item in query)
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.