c# - 一个列表中的不同属性
问题描述
我有一堂让我恶心的课。我从我的数据库中获取这些数据,只是想操纵事物并将其带回来。让我神经紧张的课程:
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>
但没有任何效果,我如何处理包含不同类型的列表?
一个解决方案是返回一个空列表,但是我什至不知道如何描述属性以使其工作。任何解决方案?
解决方案
您应该使用 Type 参数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, 34, 23
},
replace = new List<dynamic>
{
234, true, "test3"
},
index = 234
};
var jsonObject = Newtonsoft.Json.JsonConvert.SerializeObject(p);
Console.ReadKey();
}
jsonObject 有数据。
推荐阅读
- db2 - 在一个 DB2 存储过程中声明全局临时表、插入和删除语句
- javascript - 如何在创建反应应用程序中创建绝对路径?
- excel - 如何从非活动工作表中引用 VBA 中的命名范围?
- python - 编写文件,读取它们并使用不同的模块调用它们
- django - base64 编码从 .bash_profile 返回 None ,我将其保存为环境变量
- reactjs - 如何使用 useLazyQuery() 在每次点击时执行查询
- webrtc - 如何查看转向服务器日志?
- php - 返回不在父项中的子类别
- jquery - 如何使用 CodeIgniter 调试 jQuery ajax url 是否工作
- reactjs - 用 typescript 反应 CRA 不能与 eslint 一起工作