简体   繁体   English

将派生的 class object 传递给 function

[英]Passing a Derived class object to a function

I am going through the following code:我正在通过以下代码:

public interface IBus
{
  Task Publish(BaseMessage message,string topicName);
}

The BaseMessage is: BaseMessage是:

public class BaseMessage
{
  public Guid Id {get;set;}
  public DateTime CreationDateTime{get;set;}
}

There is a class which implements IBus有一个实现 IBus 的 class

public class AzureServiceBusMessageBus : IBus
{
  public async Task Publish(BaseMessage message,string topicName)
  {
    ISenderClient topic = new TopicClient(message,topicName);
    
    var jsonMess = JsonConvert.SerializeObject(message);
    var serviceBusMessage = new Message(Encoding.UTF8.GetBytes(jsonMessage))
    {
      CorrelationId = Guid.NewGuid().ToString()
    }
   await topicClient.Sendasync(serviceBusMessage);
  }

The following code is from Controller of client:以下代码来自客户端的 Controller:

public BasketCheckOutMessage : BaseMessage
{
 public string FirstName {get;set;}
}

public Task CheckController(IBus messageBus)
{
  ...
   BasketCheckOutMessage basket = new BasketCheckOutMessage ();
   try
   {
    await messageBus.Publish(basket ,"checkout");
   }
   catch(Exception e)
   {
   }
}

Here, I dont understand one thing:在这里,我不明白一件事:

What is the purpose of passing " basket " object in clientcontroller whereas it is received as " BaseMessage " base object in Publish().在客户端控制器中传递“篮子”object 的目的是什么,而它在 Publish() 中作为“ BaseMessage ”基础 object 接收。 My understanding is this is a redundant code because if we set FirstName = "A" in BasketCheckOutMessage from client code in ClientController and pass to "Publish" method, it wont be received since the argument has baseclass reference(BaseMessage).我的理解是这是一个冗余代码,因为如果我们在 ClientController 中的客户端代码中设置 BasketCheckOutMessage 中的 FirstName = "A" 并传递给“Publish”方法,则由于参数具有基类引用( BaseMessage ),因此不会收到它。

Is my understand wrong in this context?在这种情况下我的理解是错误的吗?

Yes, your understanding needs a bit of tweaking.是的,您的理解需要稍作调整。

When you pass a derived object, you are indeed passing it, with all its fields and other data.当你传递一个派生的 object 时,你确实传递了它,以及它的所有字段和其他数据。

The receiving end however can expect the base class, but if the receiver "looks into it", for instance, casts message to BasketCheckOutMessage , it would be able to use all its members.然而,接收端可以期待基本 class,但是如果接收者“调查”,例如,将message投射到BasketCheckOutMessage ,它将能够使用它的所有成员。 The message.GetType() call would also produce the typeof(BasketCheckOutMessage) output. message.GetType()调用还将产生typeof(BasketCheckOutMessage) output。

Another matter is C#'s Reflection.另一件事是 C# 的反射。 The JsonConvert.SerializeObject method will investigate which properties on the input members are available to serializing, and it will find FirstName member, because it is there. JsonConvert.SerializeObject方法将调查输入成员上的哪些属性可用于序列化,并且它将找到FirstName成员,因为它在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM