English is not my native language and I am newbie, so don't laugh at me.
I want to create a class in C# that help me to save data to file and read them easily. It works like this:
RealObject john = new RealObject("John");
john.AddCharacter("Full Name", "Something John");
john.AddCharacter("Grade", new List<double> { 9.9, 8.8, 7.7 });
await john.SaveToFileAsync("Test.ini");
RealObject student = new RealObject("John");
await student.ReadFromFileAsync("Test.ini");
Type valueType = student.GetCharacter("Grade").Type;
List<double> johnGrade = (List<double>) student.GetCharacter("Grade").Value;
The file "Test.ini" looks like this:
S_Obj_John
Name System.String Something John
Grade System.Collections.Generic.List`1[System.Double] 9.9;8.8;7.7
E_Obj_John
I have some questions:
Question 1. Can you give me some libraries that do this job for me, please?
Question 2. My code is too redundant, how can I optimize it?
2.1 Saving code: I have to write similar functions: ByteListToString, IntListToString, DoubleListToString,...
private static string ListToString(Type listType, object listValue)
{
string typeString = GetBaseTypeOfList(listType);
if (typeString == null)
{
return null;
}
switch (typeString)
{
case "Byte":
return ByteListToString(listValue);
..........
default:
return null;
}
}
private static string ByteListToString(object listValue)
{
List<byte> values = (List<byte>) listValue;
string text = "";
for (int i = 0; i < values.Count; i++)
{
if (i > 0)
{
text += ARRAY_SEPARATING_SYMBOL;
}
text += values[i].ToString();
}
return text;
}
2.2 Reading code: I have to write similar functions: StringToByteList, StringToIntList, StringToDoubleList,...
public static object StringToList(Type listType, string listValueString)
{
string typeString = GetBaseTypeOfList(listType);
if (typeString == null)
{
return null;
}
switch (typeString)
{
case "Byte":
return StringToByteList(listValueString);
..........
default:
return null;
}
}
private static List<byte> StringToByteList(string listValueString)
{
var valuesString = listValueString.Split(ARRAY_SEPARATING_SYMBOL);
List<byte> values = new List<byte>(valuesString.Length);
foreach (var v in valuesString)
{
byte tmp;
if (byte.TryParse(v, out tmp))
{
values.Add(tmp);
}
}
return values;
}
Thank you for your help