可以保存整数或字符串的C#类属性

时间:2017-06-09 20:27:27

标签: c# json class properties

我正在创建一个我需要转换为JSON的类,但我需要一个属性才能包含整数或字符串(属性值如下):

AISFormService obj = new AISFormService();

obj.formActions.Add(new FormAction { type = "New", controlID = 33, command = 
"Enter", value = "K2F" });

obj.formActions.Add(new FormAction { type = "New", controlID = 33, command = 
"Enter", value = 777 });


 public class FormAction
 {
     public string type { get; set; }
     public int controlID { get; set; }
     public string value { get; set; }
     public string command { get; set; }
 }

 public class AISFormService
 {
     public List<FormAction> formActions = new List<FormAction>();
     public string Role { get; set; }
     public string DeviceName { get; set; }
     public string Token { get; set; }
     public string MaxPageSize { get; set; }
  }

2 个答案:

答案 0 :(得分:1)

一种方法是,你可以为value类型的Object属性实例,但是你将失去类型安全性,当你访问价值时,你需要检查它的类型首先喜欢:

public Object value { get; set; }

现在您可以在其中存储任何类型的值:

obj.formActions.Add(new FormAction { type = "New", controlID = 33, 
                                     command ="Enter", value = "K2F" });

obj.formActions.Add(new FormAction { type = "New", controlID = 33, 
                                     command = "Enter", value = 777 });

在您的情况下stringint,但在将其转换为特定类型之前,您必须先检查以确保安全:

if(value is int)
{
  var integerValue = Convert.ToInt32(value);
}
if(value is String)
{
  var stringValue = Convert.ToString(value);
}

希望它有所帮助!

答案 1 :(得分:0)

如果您正在使用&#34;公共字符串值{get;组; }&#34;然后它会正常工作。意味着当您将新属性添加到FormAction模型时,您可以简单地将整数转换为字符串。见下文

obj.formActions.Add(new FormAction { type = "New", controlID = 33, command = 
"Enter", value = "K2F" });

obj.formActions.Add(new FormAction { type = "New", controlID = 33, command = 
"Enter", value = "777" });

当您获取它时,您可以使用Convert.ToInt32()将该字符串类型转换为整数类型。我希望它对你有用。如果您有任何其他疑问,请与我们联系。