System.InvalidCastException: cannot discard an object of type x for input y

I have a custom messaging system that I am trying to convert so that it can support plugins.

There are manufacturers and consumers in the system. Both must indicate the type of message they produce or consume.

For consumers, the interface to be implemented is

IConsumer<AMessage>

I have a consumer in a dll plugin that implements this interface:

FileProcessor : IConsumer<FileMessage>

WITH

FileMessage : AMessage

And AMessage is an abstract class. Both IConsumer and AMessage are in the main assembly.

Now, in the kernel that downloaded the plugin and scanned and found consumers, I want to associate consumers with the messaging system.

To simplify the situation, I'm just trying to put the consumer in a variable:

IConsumer<AMessage> consumer = IConsumer<AMessage> new FileProcessor();

I get a warning in VS:

: , , "TestPlugin.FileProcessor" "Core.IConsumer".

,

System.InvalidCastException: "TestPlugin.FileProcessor" "Core.IConsumer`1 [Core.AMessage]".

? ?

- edit1 -

, IProducer IConsumer:

public interface IProducer<out T> : IProcessor where T : AMessage
{
    event MessageSender<T> SendMessage;
}

public interface IConsumer<in T> : IProcessor where T : AMessage
{
    ProcessResult ProcessBean(T bean);
}

, T, T. :

var channel = flow.From(FileProducer).To(FileConsumer);

. :

public Channel<T> From<T>(IProducer<T> producer) where T : AMessage
{
    ...
}

channel.To:

public class Channel<T> where T : AMessage 
{

   public Channel<T> To(IConsumer<T> consumer){
      ...
   }
}

, T .

- edit1 -

- edit2 -

, JSON .

, ( ) ( ):

var consumers = new Dictionary<string, IProcessor>();

IConsumer , T .

id ( ) To (...) . , IProcessor, "To" public Channel<T> To(IConsumer<T> consumer).

- edit2 -

- -

Luaan (. ) :

<string, IProcessor>, <string, dynamic>, !

, !

@Luaan, , ...

- -

!

+4
2

covariant out:

IConsumer<out AMessage>

, , , FileMessage, AMessage.

, , (IConsumer<in AMessage>), :

IConsumer<AMessage> consumer = (IConsumer<AMessage>)new FileProcessor();

. msdn:

( ) , . IEnumerable <Base> IEnumerable <Derived> .

+2

IConsumer<T> T , ( .NET 4 ):

public interface IConsumer<out T>

:

IConsumer<AMessage> consumer = new FileProcessor();

T, . , ., , IList<T>: IList<Animal> cats = new List<Cat>() , cats.Add(new Dog()), .:)

0

All Articles