簡體   English   中英

使用C#反射將可變大小的集合分配給類屬性

[英]Using C# Reflection to assign collection of variable size to class properties

我有一個名為Foo的目標類,具有以下屬性:

public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
public string Bar5 { get; set; }
public string Bar6 { get; set; }

我正在讀取一個文件,該文件可以具有任意數量的“ Bars”,並將其讀取到名為fileBars的集合中。 我需要找出如何使用反射來遍歷fileBars並指定第一個Bar1 ,第二個到Bar2等。

我已經嘗試了一些在網上找到的東西,最近一次是按照下面顯示的方法進行的,但是我沒有任何運氣。 熟悉反射的人能指出我正確的方向嗎?

var count = fileBars.Count();
var myType = Foo.GetType();
PropertyInfo[] barProperties = null;

for (var i = 0; i < count; i++)
{
    barProperties[i] = myType.GetProperty("Bar" + i + 1);
}

您需要初始化barProperties

PropertyInfo[] barProperties = new PropertyInfo[count];

要將值分配給屬性,請使用SetValue

barProperties[i].SetValue(Foo, fileBars[i] );

我認為您不需要將PropertyInfo對象存儲在數組中; 您可以隨便分配值:

var count = fileBars.Count();
var instance = new Foo();

for (var i = 1; i <= count; i++)
{
    var property = typeof(Foo).GetProperty("Bar" + i);
    if(property != null)
       property.SetValue(instance, fileBars[i - 1];
    else 
       // handle having too many bars to fit in Foo

}

除非以后需要保留找到的所有屬性,否則不需要barProperties數組:

var myType = foo.GetType();
int barCount = 0;
foreach(string barValue in fileBars)
{
    barCount++;
    var barProperty = myType.GetProperty("Bar" + barCount);
    barProperty.SetValue(foo, barValue, null);
}

暫無
暫無

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

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