示例#1
0
        public T Map(ParsedData data)
        {
            T instance = Activator.CreateInstance <T>();

            if (_params.Count == 0)
            {
                return(instance);
            }

            Type t = typeof(T);

            PropertyInfo[] myMembers = t.GetProperties().ToArray();

            foreach (PropertyInfo propertyInfo in myMembers)
            {
                if (!_params.ContainsKey(propertyInfo.Name))
                {
                    continue;
                }

                RecordParamAttribute attr = _params[propertyInfo.Name];

                Type   t2 = propertyInfo.PropertyType;
                object value;
                if (_params[propertyInfo.Name].ByName)
                {
                    value = data.GetValue <string>(attr.Name);
                }
                else
                {
                    if (!attr.Index.HasValue)
                    {
                        throw new ArgumentException($"Index not defined for property {propertyInfo.Name}");
                    }

                    value = data.GetValue <string>(attr.Index.Value);
                }

                // Additional filters
                if (attr.Brackets != Brackets.None)
                {
                    value = value.ToString().Substring(1, value.ToString().Length - 2);
                }

                // Target type transformation
                if (value != null && t2 != typeof(string))
                {
                    value = Convert.ChangeType(value, t2);
                }

                propertyInfo.SetValue(instance, value);
            }

            return(instance);
        }
        public void Get()
        {
            string raw = "val1=1\tval2=TestMessage";

            ParsedData data = ParseService.Parse(raw);

            string result1 = data.GetValue <string>("val2");

            Assert.IsType <string>(result1);

            int result2 = data.GetValue <int>("val1");

            Assert.IsType <int>(result2);
        }
        public void GetParam_WrongIntParam_Exception()
        {
            string     raw  = "val1=1\tval2=TestMessage";
            ParsedData data = ParseService.Parse(raw);

            Assert.Throws <InvalidCastException>(() => data.GetValue <int>("val3"));
        }
        public void Get_ValueWithoutParam()
        {
            string     raw  = "val1=1\tval2=TestMessage\tval4";
            ParsedData data = ParseService.Parse(raw);

            string result2 = data.GetValue <string>(3);

            Assert.Equal("val4", result2);
        }
        public void Get_NotExistedParam_Null()
        {
            string     raw  = "val1=1\tval2=TestMessage";
            ParsedData data = ParseService.Parse(raw);

            string result1 = data.GetValue <string>("val3");

            Assert.Null(result1);
        }