0

我基本上是将值保存并加载到数组中以输入 JSON 库,我只是在寻找一种更优雅的方法来执行此操作:

类属性到数组

 return new object[] { path, pathDir, name };

数组到类属性

c.path = values[0];
c.pathDir = values[1];
c.name = values[2];

理想情况下不需要额外运行时开销(例如反射)的简单解决方案值得赞赏。

我可以做这样的事情吗?

  c.{path, pathDir, name} = values[0...2]

编辑:我特别要求数组。我知道序列化、JSON 和 Protobuf 以及其他所有人的建议。

4

1 回答 1

1

这不是诀窍吗?

return  new {path= "/Some/Path", pathDir= "SiteRoot", name="MyPath"}

编辑:

 //Mock function to simulate creating 5 objects with 'CreateArrayOb' function
        public void CreatingObjects()
        {
            var lst = new List<object>();
            for (var x = 0; x < 5; x++)
            {
                lst.Add(CreateArrayOb(new string[] {"Path" + x, "Dir" + x, "Path" + x}));
            }
        }
        public object CreateArrayOb(object[] vals)
        {
            if (vals != null && vals.Any())
            {
                //Switch cases in the event that you would like to alter the object type returned
                //based on the number of parameters sent
                switch (vals.Count())
                {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        return new { path = vals.ElementAt(0), pathDir = vals.ElementAt(1), name = vals.ElementAt(2) };
                }

            }
            return null;
        }
于 2012-12-03T15:21:47.267 回答