繁体   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