小编bsc*_*eck的帖子

在不知道类型的情况下返回通用对象?

我对编程还很陌生,并且一直负责创建一个 WebHook 使用者,该使用者接受原始 JSON 字符串,将 JSON 解析为一个对象,该对象将被传递到处理程序中进行处理。JSON 是这样输入的:

{
   "id":"1",
   "created_at":"2017-09-19T20:41:23.093Z",
   "type":"person.created",
   "object":{
      "id":"person1",
      "created_at":"2017-09-19T20:41:23.076Z",
      "updated_at":"2017-09-19T20:41:23.076Z",
      "firstname":"First",
      ...
   }
}
Run Code Online (Sandbox Code Playgroud)

内部对象可以是任何对象,所以我认为这将是使用泛型的好机会,并按如下方式构建我的类:

public class WebHookModel<T> where T : class, new()
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "created_at")]
    public DateTime CreatedAt { get; set; }

    [JsonProperty(PropertyName = "type")]
    public string Type { get; set; }

    [JsonProperty(PropertyName = "object")]
    public T Object { get; set; }

    [JsonIgnore]
    public string WebHookAction
    {
        get
        {
            return string.IsNullOrEmpty(Type) ? …
Run Code Online (Sandbox Code Playgroud)

c# generics factory-pattern

5
推荐指数
1
解决办法
904
查看次数

标签 统计

c# ×1

factory-pattern ×1

generics ×1