U
U
UbgFHgMOIgkTrP7Sj8GJ2021-03-20 11:02:58
Parsing
UbgFHgMOIgkTrP7Sj8GJ, 2021-03-20 11:02:58

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; }
}


And there is an input string
0, 1.1, 1.2, 1.3, name, true

Is it possible to somehow create an object of the class MyClassand 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

4 answer(s)
E
edward_freedom, 2021-03-20
@UbgFHgMOIgkTrP7Sj8GJ

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));
            }

        }
    }

#
#, 2021-03-20
@mindtester

No

B
BasiC2k, 2021-03-20
@BasiC2k

Only if it is json. It can be serialized into a class.

D
d-stream, 2021-03-20
@d-stream

Lazy: "turn" the string into json in any banal way and serialize / deserialize the resulting json (split and don't give a shit with stringBuilder in the loop, adding opening / closing brackets)
Advanced: write your own serializer / deserializer for csv )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question