具有可以是两种不同类型之一的属性的类 [英] Class with property that can be one of two different types

查看:40
本文介绍了具有可以是两种不同类型之一的属性的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#开发Telegram机器人,但难以实现 Message 类型。根据 API文档聊天字段可以是 User 类型,也可以是 GroupChat 类型。

I'm developing a Telegram bot in C# but have difficulty with implementing Message type. According to API documentation, chat field can be either of type User or of type GroupChat. How do I implement that in C#?

到目前为止,我只能使用 Newtonsoft.Json 提出以下代码:

So far I could only come up with following code using Newtonsoft.Json:

public class Update {
....
  [JsonProperty("chat")]
  public User chat { get; set; }

  [JsonProperty("chat")]
  public GroupChat group_chat { get; set; }
....
}

但它不适用于我的WebAPI 2控制器方法,因为我使用 FromBody 属性反序列化 Message

But it doesn't work with my WebAPI 2 controller method since I deserialize Message using FromBody attribute:

public async Task<HttpResponseMessage> Post(string token, [FromBody] Update update)

(类型 Update 的字段 message 的类型为 Message

(type Update has a field message of type Message)

是否有更好的方法来实现 Message 类型?

Is there any better way to implement Message type?

推荐答案

由于您应该在一个字段中处理看似完全不同的两个对象,所以我认为您不能使用强类型的对象,但可以对聊天字段使用动态类型,例如

Since you are supposed to handle seemingly two completely different objects in one field I don't think you can use strongly-typed objects but you can use a dynamic type for the chat field such as

public class Telegram
{
    public int message_id { get; set; }
    public dynamic chat { get; set; }
}

然后,您可以访问变量并检查它们是否为空了解是用户聊天还是群聊:

Then you can access the variables and check if they are null or not to understand if it's a user or a group chat:

static void Main(string[] args)
{
    string json = @"{ ""chat"": { ""id"": 1, ""first_name"": ""my_first_name"", ""last_name"": ""my_last_name"",  ""username"": ""my_username"" }, ""message_id"": 123 }";
    var telegram = Newtonsoft.Json.JsonConvert.DeserializeObject<Telegram>(json);
    string name = telegram.chat.first_name; // name = my_first_name
    string title = telegram.chat.title; // title = null
}

这篇关于具有可以是两种不同类型之一的属性的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆