问题描述
我正在自动为商店类的属性编写一个 PropertyInfo
列表。但它的表现很奇怪。这是我写的:
属性类:
public class ValueLib
{
public int Value1 { get; set; }
public string Value2 { get; set; }
public bool Value3 { get; set; }
}
public class InfoLib
{
public System.Reflection.PropertyInfo Info { get; set; } // Store PropertyInfo of properties in ValueLib.
}
我希望创建一个列表 List<InfoLib>
来存储信息。当我打印 InfoLib.Info
时应该有这个结果:
Int32 Value1
String Value2
Boolean Value3
这是主要脚本:
public class Program
{
public ValueLib ValueLib { get; set; }
private static List<InfoLib> _infoLib;
public static List<InfoLib> InfoLib
{
get
{
_infoLib = _infoLib ?? new List<InfoLib>(Enumerable.Repeat(new InfoLib(),typeof(ValueLib).GetProperties().Length).ToList()); // Initialize list using Enumerable. ------(1)
_infoLib.ForEach(p => p.Info = typeof(ValueLib).GetProperties()[_infoLib.IndexOf(p)]); // Check every properties and stored the corresponding PropertyInfo.
return _infoLib;
}
set { _infoLib = value; }
}
public static void Main(string[] args)
{
InfoLib.ForEach(p => Console.WriteLine(p.Info)); // Print every propertyInfo.
}
}
在编译这个程序时,它想出了这个,这是我没想到的:
Int32 Value1
Int32 Value1
Int32 Value1
经过多次尝试,我发现用此脚本替换 (1)
时可以正常工作:
if(_infoLib != new List<InfoLib>(Enumerable.Repeat(new InfoLib(),typeof(ValueLib).GetProperties().Length)))
{
_infoLib = new List<InfoLib>();
// Use normal for loop to initialize the list
for(int i = 0; i < typeof(ValueLib).GetProperties().Length; i++)
{
_infoLib.Add(new InfoLib());
}
}
看起来可行,但我想知道我的原始脚本有什么问题。感谢您的回复。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)