Answer the question
In order to leave comments, you need to log in
How to create object from parameter string?
There is a class like this
public class MyClass
{
private int Id { get; set; }
private double X { get; set; }
private double Y { get; set; }
private double Z { get; set; }
private string Name { get; set; }
private bool Active { get; set; }
}
0, 1.1, 1.2, 1.3, name, true
MyClass
and not convert each parameter to the appropriate data type when the constructor is called?
Answer the question
In order to leave comments, you need to log in
Of course it is possible. The number of values must be consecutive and match the number of properties in the class.
var data = "0, 1.1, 1.2, 1.3, name, true";
var myClass = MyClass.Parse(data);
MyClass.SeeChanges(myClass);
public class MyClass
{
private int Id { get; set; }
private double X { get; set; }
private double Y { get; set; }
private double Z { get; set; }
private string Name { get; set; }
private bool Active { get; set; }
public static MyClass Parse(string data)
{
var myClass = new MyClass();
var properties = data.Split(',');
var props = myClass.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static);
for (int i = 0; i < props.Length; i++)
{
var prop = props[i];
var type = prop.PropertyType;
prop.SetValue(myClass, Convert.ChangeType(properties[i], type, CultureInfo.InvariantCulture));
}
return myClass;
}
public static void SeeChanges(MyClass myClass)
{
var props = myClass.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static);
foreach (var prop in props)
{
Debug.WriteLine("{0} = {1}", prop.Name, prop.GetValue(myClass, null));
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question