I am writing a list of PropertyInfo
for store class's properties automatically. But it perform weirdly. This is what I wrote:
Class for properties:
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.
}
I'm expecting create a list List<InfoLib>
to store the information. Which should have this result when I print InfoLib.Info
:
Int32 Value1
String Value2
Boolean Value3
Here is the main script:
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.
}
}
When compile this program, it come up with this, which I didn't expect:
Int32 Value1
Int32 Value1
Int32 Value1
After a several attempt, I found it work when replacing (1)
with this script:
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());
}
}
It seems work but I wonder what's wrong with my original script. Thank you for any replies.