如何解决一个列表中的不同属性
我有一堂课让我恶心。 我从我的数据库中获取这些数据,只是想操纵事物并将其带回来。 让我神经崩溃的课程:
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,""
],"replace": [
false,or different one like this:
"install": [
false,2,3
],
我用问题标记了属性。在此属性中可以是布尔值、字符串和/或整数。
我尝试创建 List<dynamic>
、List<object>
但没有任何效果,我该如何处理包含不同类型的列表?
一个解决方案是返回一个空列表,但我什至不知道如何描述属性以使其工作。任何解决方案?
解决方法
您应该使用类型参数 T
和 U
,并且可以在初始化和声明对象时将它们替换为类型。
零件类代码
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,23
},replace = new List<dynamic>
{
234,true,"test3"
},index = 234
};
var jsonObject = Newtonsoft.Json.JsonConvert.SerializeObject(p);
Console.ReadKey();
}
jsonObject 有数据。
,处理不同类型列表的唯一可能方法是使用最低的公共类型,在这种情况下可能是 object
(dynamic
也会 em> 工作,但对 object
没有明显的好处)。这是此工作的示例:
var input = "[false,false,123,\"foo\"]";
var result = JsonConvert.DeserializeObject<List<object>>(input);
foreach(var item in result)
{
Console.WriteLine(item);
}
现场示例:https://dotnetfiddle.net/LOYEWa
因此您的类必须将这 2 个列表定义为 List<object>
才能进行反序列化
public class Part
{
...
public List<object> install { get; set; } // No problem here
public List<object> replace { get; set; } // Nor here
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。