首页 > 解决方案 > 一个列表中的不同属性

问题描述

我有一堂让我恶心的课。我从我的数据库中获取这些数据,只是想操纵事物并将其带回来。让我神经紧张的课程:

public class Part
{
    public string name { get; set; }
    public bool horizontal { get; set; }
    public bool @abstract { get; set; }
    public bool orientationChangable { get; set; }
    public int? shared { get; set; }
    public int count { get; set; }
    public int size { get; set; }
    [JsonProperty(PropertyName = "alu")]
    public bool alu { get; set; }
    [JsonProperty(PropertyName = "paint")]
    public bool? paint { get; set; }
    [JsonProperty(PropertyName = "glue")]
    public bool? glue { get; set; }
    public List<> install { get; set; } // Problem here
    public List<> replace { get; set; } // And here
    public int index { get; set; }

一个对象可以是这样的:

"install": [
        false,
        false,
        false,
        ""
      ],
      "replace": [
        false,
        false,
        false,
        ""
      ],

or different one like this:

"install": [
        false,
        2,
        ""
      ],
      "replace": [
        false,
        false,
        3
      ],

我用问题标记了属性。在此属性中,可以是布尔值、字符串和/或整数。

我尝试制作List<dynamic>List<object>但没有任何效果,我如何处理包含不同类型的列表?

一个解决方案是返回一个空列表,但是我什至不知道如何描述属性以使其工作。任何解决方案?

标签: c#listobjectproperties

解决方案


您应该使用 Type 参数TU并且可以在初始化和声明对象时将它们替换为类型。

零件类代码

public class Part<T, U>
{
        public string name { get; set; }
        public bool horizontal { get; set; }
        public bool @abstract { get; set; }
        public bool orientationChangable { get; set; }
        public int? shared { get; set; }
        public int count { get; set; }
        public int size { get; set; }
        [JsonProperty(PropertyName = "alu")]
        public bool alu { get; set; }
        [JsonProperty(PropertyName = "paint")]
        public bool? paint { get; set; }
        [JsonProperty(PropertyName = "glue")]
        public bool? glue { get; set; }
        public List<T> install { get; set; } // Problem solved by using T
        public List<U> replace { get; set; } // And also this one
        public int index { get; set; }
    } 

我已经用一些随机数据对其进行了初始化。

static void Main(string[] args)
        {

            Part<dynamic, dynamic> p = new Part<dynamic, dynamic>()
            {
                name = "test",
                horizontal = true,
                @abstract = true,
                orientationChangable = false,
                shared = 12,
                count = 20,
                size = 23,
                alu = true,
                paint = true,
                glue = true,
                install = new List<dynamic>
                {
                    "Hello" , 34, 23, 34, 23
                },
                replace = new List<dynamic>
                {
                    234, true, "test3"
                },
                index = 234
            };

            var jsonObject = Newtonsoft.Json.JsonConvert.SerializeObject(p);
            Console.ReadKey();
        }

jsonObject 有数据。


推荐阅读