使用C#反射将可变大小的集合分配给类属性
我有一个名为使用C#反射将可变大小的集合分配给类属性,c#,reflection,C#,Reflection,我有一个名为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; } 我正在读取一个文件,其中可能有任意数量的“条”,我将其读入
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; }
我正在读取一个文件,其中可能有任意数量的“条”,我将其读入名为filebar
的集合。我需要了解如何使用反射来迭代文件栏
,并将第一个分配给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);
}
var count=filebar.count();
var myType=Foo.GetType();
PropertyInfo[]barProperties=null;
对于(变量i=0;i
您需要初始化酒吧属性
:
PropertyInfo[] barProperties = new PropertyInfo[count];
要为属性指定值,请使用SetValue
:
barProperties[i].SetValue(Foo, fileBars[i] );
您需要初始化
barProperties
:
PropertyInfo[] barProperties = new PropertyInfo[count];
要为属性指定值,请使用SetValue
:
barProperties[i].SetValue(Foo, fileBars[i] );
我认为您不需要将
属性info
对象存储在数组中;您可以边走边指定值:
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
}
var count=filebar.count();
var instance=newfoo();
对于(var i=1;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
}
var count=filebar.count();
var instance=newfoo();
对于(var i=1;i,除非需要保留以后找到的所有属性,否则不需要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);
}
除非需要保留以后找到的所有属性,否则不需要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);
}
为什么不使用单个字符串[]
或ICollection
属性?请注意,您构建的属性名称不正确。现在,您将构建“Bar01”、“Bar11”、“Bar21”。您需要使用“Bar”+(i+1)
@ChrisSinclair不确定我是如何漏掉它的。谢谢!为什么不使用单个字符串[]
或ICollection
属性?请注意,您构建的属性名称不正确。现在,您将构建“Bar01”、“Bar11”、“Bar21”。您需要具有“Bar”+(i+1)
@ChrisSinclair不确定我是怎么漏掉的。谢谢!我收到一个错误,说类名Foo在SetValue行的这一点上无效。他指的是typeof(Foo)
,因为你在你的问题中使用Foo.GetType()
,我假设Foo
是一个实例。如果Foo
是一个类型,那么就使用typeof(Foo)
取而代之。我得到一个错误,说类名Foo在SetValue行的这一点上无效。他的意思是typeof(Foo)
,因为你在你的问题中使用Foo.GetType()
我假设Foo
是一个类型。如果Foo
是一个类型,那么就改用typeof(Foo)
。