.net 如何根据类的类型转换属性

lnlaulya  于 2023-05-08  发布在  .NET
关注(0)|答案(1)|浏览(176)

我正在将一个应用程序与另一个应用程序集成。我遇到一个问题,应用程序B通过Rest请求从应用程序A接收响应。
我得到的对象是DiscountCodeNode类型:

public class DiscountCodeNode {

   public DiscountCode codeDiscount { get; set; }
   public string id { get; set; }
}

DiscountCode类型的可能概率为DiscountCodeAppDiscountCodeBasicDiscountCodeBxgyDiscountCodeFreeShipping
如何在将对象反序列化为DiscountCodeNode时知道DiscountCode的类型
我试着把codeDiscount类型设为object,但是我又怎么知道这个对象的类型是什么呢?

zsohkypk

zsohkypk1#

接口实现是一条路要走,我会实现Discount类之间的接口,我会强制DiscountNode类实现接口,你可以在下面找到一个例子:

using System;

namespace StackOverflow
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var discountCodeBxgy = new DiscountCodeBxgy() { Code = "Bxgy" };

            var discountCodeNode = new DiscountCodeNode { Id = "MyId", CodeDiscount = discountCodeBxgy };

            if (discountCodeNode.CodeDiscount is DiscountCodeBxgy Bxgy)
            {
                Console.WriteLine(Bxgy.Code);
            }
            // Just to prove it is right! --> this message will not be shown in the console app
            if (discountCodeNode.CodeDiscount is DiscountCodeApp App)
            {
                Console.WriteLine(App.Code);

            }

            Console.ReadLine();
        }

       
    }

    internal class DiscountCodeNode
    {
        public IDiscountCode CodeDiscount { get; set; }
        public string Id { get; set; }
    }

    internal class DiscountCodeApp : IDiscountCode
    {
        public string Code { get; set; }

    }

    internal class DiscountCodeBasic : IDiscountCode
    {
        public string Code { get; set; }

    }

    internal class DiscountCodeBxgy: IDiscountCode
    {
        public string Code { get; set; }

    }

    internal class DiscountCodeFreeShipping : IDiscountCode
    {
        public string Code { get; set; }

    }
    internal interface IDiscountCode
    {
        string Code { get; set; }
    }
}

最后,由于模式匹配,您将在控制台中输出“Bxgy”,这意味着它已经工作,如下图所示:

希望能帮上忙
问候
米格尔

相关问题