如何在C#接口中实现泛型?

时间:2019-06-27 03:20:19

标签: c# generics interface

嗨,我正在尝试在C#接口中实现泛型。在实现泛型之后,我有一种方法应采用不同的模型作为参数。下面是我的界面。

 public interface IKafkaProducer<T>
  {
    Task ProduceAsync(T kafkaEvent, string topicName);
  }

在实现泛型之后,此Kafka事件可能应该是不同的模型。例如,它应该能够接受Employee或User类等。下面是我的类实现。

public class KafkaProducer<T> : IKafkaProducer<T>
  {
   public async Task ProduceAsync(T kafkaEvent, string topicName)
    {
      using (var schemaRegistry = new CachedSchemaRegistryClient(this.kafkaSchemaRegistryConfig.GetConfig()))
      using (var producer =
               new ProducerBuilder<string, ProductRangeEvent>(this.producerConfigFactory.ProducerConfig())
                   .SetKeySerializer(new AvroSerializer<string>(schemaRegistry))
                   .SetValueSerializer(new AvroSerializer<ProductRangeEvent>(schemaRegistry))
                   .Build())
      {
        Console.WriteLine($"{producer.Name} producing on {topicName}. Enter user names, q to exit.");
        await producer
              .ProduceAsync(topicName, new Message<string, ProductRangeEvent> { Key = null, Value = kafkaEvent })
              .ContinueWith(task => task.IsFaulted
                  ? $"error producing message: {task.Exception.Message}"
                  : $"produced to: {task.Result.TopicPartitionOffset}");
      }
    }
  }

在上面的代码中,ProduceAsync(topicName, new Message<string, ProductRangeEvent> { Key = null, Value = kafkaEvent })值= kafkaEvent提供了错误。该kafkaEvent类型为ProductRangeEvent。这给了我错误,无法将T类型隐式转换为ProductRangeEvent。 我将上述方法称为

public class TestController
  {
    private readonly IKafkaProducer kafkaProducer;

    public TestController(IKafkaProducer kafkaProducer)
    {
      this.kafkaProducer = kafkaProducer;
    }
     [HttpGet]
        [Route("/api/test")]
        public IActionResult Test()
        {
          ProductRangeEvent productRangeEvent = new ProductRangeEvent
          {
            id = "101"
          };
          var response = this.kafkaProducer.ProduceAsync(productRangeEvent, "users");
          response.Wait();
          var hi = response.IsCompletedSuccessfully;
          return null;
        }
      }

在上面的代码中,私有只读IKafkaProducer kafkaProducer;也给我错误使用通用类型IKafkaProducer时需要一个参数。 有人可以帮我解决此问题吗?任何帮助,将不胜感激。谢谢

1 个答案:

答案 0 :(得分:2)

更改此行:

private readonly IKafkaProducer kafkaProducer;

收件人

private readonly IKafkaProducer<ProductRangeEvent> kafkaProducer;