Skip to main content
 首页 » 编程设计

c#之使用 C# 反射将可变大小的集合分配给类属性

2024年01月28日29三少

我有一个名为 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; } 

我正在读取一个文件,该文件可能包含任意数量的“条”,我将其读入名为 fileBars 的集合中。我需要了解如何使用反射遍历 fileBars 并将第一个分配给 Bar1,第二个分配给 Bar2,等等。

我已经尝试了一些我在网上找到的东西,最近玩的是下面显示的东西,但我没有任何运气。熟悉 Reflection 的人能给我指出正确的方向吗?

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); 
} 

请您参考如下方法:

我认为您不需要将 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 
 
}