簡體   English   中英

遍歷字典並使用 value 遍歷 class C#

[英]Iterate through a dictionary and use value to iterate through class C#

在我的 c# 代碼中,我對Dictionary進行了迭代,並希望使用Classes來實現類似的目標

MyModel othermodel = new MyModel();

Dictionary<string, string> mydictionary = new Dictionary<string, string>()
{
    {"n1", "Item"},
    {"n2", "Second"},
    {"n3", "Third"},
    {"n4", "Fourth"},
    {"n5", "Fith"},
    {"n6", "Sixth"},
    {"n7", "Seventh"},
    {"n8", "Eighth"},
    {"n9", "Ninth"},
    {"n0", "Tenth"},
    {"n11", "Eleventh"}

};

foreach (var dicitem in mydictionary.ToArray())
{
    foreach (MyModel.NewItem.(mydictionary[dicitem].Value) item in othermodel.(mydictionary[dicitem].Key))
    {
         ...
    }
}

所以我的結果是:

first iteration:

foreach (MyModel.NewItem.Item item in othermodel.n1)
{
     ...
}

second iteration:

foreach (MyModel.NewItem.Second item in othermodel.n2)
{
     ...
}

...

如果有辦法做到這一點,任何幫助將不勝感激。

通過其名稱訪問 object 屬性可以使用反射來完成,無論這些名稱來自何處(字典,數組,...)

這里的小例子:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

然后訪問您執行的Name屬性:

var me = new Person {Name = "John", Age = 33};

var propertyName = "Name";
var propertyInfo = typeof(Person).GetProperty(propertyName);

var propertyValue = propertyInfo?.GetValue(me) as string;

使用上面的代碼,您可以創建一個 Propertyinfo。

如果要讀取同一 object 的更多屬性,最好一次讀取所有 PropertyInfo 對象:

var me = new Person {Name = "John", Age = 33};

var propertiesInfo = typeof(Person).GetProperties();

var propertyName = "Name";
var nameProperty = propertiesInfo
    .Single(p => p.Name == propertyName);
var name = nameProperty.GetValue(me) as string;


//faster approach
var age = (int)propertiesInfo
    .Single(p => p.Name == "Age")
    .GetValue(me);

請注意,在此示例中,我假設具有特定名稱的屬性存在,因此我簡稱為Single 但是,在不同的情況下,可能需要您在訪問之前檢查財產的存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM