This question already has an answer here:
I need to get all values of all properties of a class element/item that has been previously populated with data. Class example:
public class MyClass
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public string prop3 { get; set; }
public string prop4 { get; set; }
}
Somewhere in my code I have:
MyClass myClass = new MyClass();
List<MyClass> myList = new List<MyClass>();
MyClass myElement = new MyClass()
{
prop1 = "A",
prop2 = "B",
prop3 = "C",
prop4 = "D",
};
myList.Add(myElement);
string wholeString_opt1 =
myElement.prop1 + "\t" +
myElement.prop2 + "\t" +
myElement.prop3 + "\t" +
myElement.prop4 + "\t";
In my case the order in which I add all property values is fundamental (from first property to the last property it must have that sequence). The example shows a simple unique element list. The properties of my class are very similar (all start with prop) but in many cases the names are not alphabetically ordered in the class. This means that, if I have a considerable amount of properties in my class with different starting chars, the result of the 'wholeString_opt1' will be right if I sort the properties but it is very labor intensive.
An alternative would be something like:
PropertyInfo[] myClassProperties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in myClassProperties)
{
wholeString_opt2 += property.GetValue(myElement).ToString() + "\t";
}
Where 'wholeString_opt2' would have the same result but only if the properties of the class are, as shown above. If we have, e.g.:
MyClass myElement = new MyClass()
{
prop1 = "A",
prop2 = "B",
anotherProp3 = "C",
prop4 = "D",
};
The sorting of the .GetProperties() will be lost.
Is there any way we can overcome this problem? I might have cases with more than 25 properties... Maybe there is even other options?
Aucun commentaire:
Enregistrer un commentaire