将派生类传递给方法

问题描述 投票:0回答:1

这里是新手,试图找出实现以下目标的最佳方法:

有一个基类:

public class MessageBaseDto
{
    public string AssetId { get; set; }
}

和2个派生类:

public class DataMessageBaseDto:MessageBaseDto
{
    public string AssetType { get; set; }
    public long StartDate { get; set; }
    public long EndDate { get; set; }
}
public class CalculationMessageBaseDto:MessageBaseDto
{
    public int BatchId { get; set; }
    public bool IsCacheReady { get; set; }
    public string MetricName { get; set; }
    public int MetricVersion { get; set; }
}

还有使用派生类作为属性的类:

public class CommandServiceBusMessage<T> where T : MessageBaseDto
{ 
    [JsonPropertyName("command")]
    public CommandType Command { get; set; }

    [JsonPropertyName("payload")]
    public T Payload { get; set; }

    [JsonPropertyName("correlationId")]
    public Guid CorrelationId { get; set; }
}

还有一个方法需要接受具有从基本 MessageBaseDto 类型派生的属性的任何消息:

Task SendMessageAsync(CommandServiceBusMessage<MessageBaseDto> msg, string sendToDestinationTopic);

我正在尝试弄清楚这是否可以按照我开始的方式实现?目前,当我调用该方法时,出现错误:

var messageToSend = new CommandServiceBusMessage<CalculationMessageBaseDto>();
messageToSend.Command = CommandType.CalculateAlgorithm;
messageToSend.CorrelationId = serviceBusMessage.CorrelationId;
messageToSend.Payload = new CalculationMessageBaseDto();

await SendMessageAsync(messageToSend, _senderCalcTopicName);

Severity   Code    Description Project File    Line    Suppression State Error   CS1503  Argument 1: cannot convert from 'DeBeers.Analytics.Orchestration.Domain.Dtos.CommandServiceBusMessage<DeBeers.Analytics.Orchestration.Domain.Dtos.CalculationMessageBaseDto>' to 'DeBeers.Analytics.Orchestration.Domain.Dtos.CommandServiceBusMessage<DeBeers.Analytics.Orchestration.Domain.Dtos.MessageBaseDto>' DeBeers.Analytics.Orchestration.Service C:\Users\boguss\source\repos\analytics-orchestration-service\DeBeers.Analytics.Orchestration.Service\Services\ServiceBusTopicSubscription.cs    81  Active

c# generics polymorphism derived-class
1个回答
0
投票

要解决您的问题,您需要更改函数“SendMessageAsync”的定义。这是您应该使用的正确定义:

public async Task SendMessageAsync<T>(CommandServiceBusMessage<T> msg, string sendToDestinationTopic) 
    where T: MessageBaseDto 
{
    // Do something here
}

希望有帮助!

工作示例:https://dotnetfiddle.net/zKVBLV

© www.soinside.com 2019 - 2024. All rights reserved.