Вопрос

I have the following code:

public class EntityFilter<T>
{}

public interface IEntity
{}

public class TestEntity : IEntity
{}

class Program
{
    static void Main(string[] args)
    {   
        var ef = new EntityFilter<TestEntity>();

        DoSomething((EntityFilter<IEntity>)ef); // <- casting fails
    }

    public static void DoSomething(EntityFilter<IEntity> someEntityFilter)
    {
    }
}

Visual Studio says:

Cannot convert type 'ConsoleApplication1.EntityFilter<ConsoleApplication1.TestEntity>' to 'ConsoleApplication1.EntityFilter<ConsoleApplication1.IEntity>'

I cannot convert the DoSomething method to be generic and accept EntityFilter<T> because in my application the type of T is unknown at the moment of DoSomething call. The type will be determined later inside of DoSomething using reflection.

How can I pass the ef variable to the DoSomething method without making the DoSomething method generic?

Это было полезно?

Решение

If EntityFilter<T> could be derived from an interface and that interface had a covariant generic parameter, you could do what you are asking without generics in the method.

Notice the "out" keyword in the IEntityFilter<out T> definition.

public class Program
{
    static void Main(string[] args)
    {
        var ef = new EntityFilter<TestEntity>();

        DoSomething(ef);
    }

    public static void DoSomething(IEntityFilter<IEntity> someEntityFilter)
    {
    }
}

public interface IEntityFilter<out T>
{ }

public class EntityFilter<T> : IEntityFilter<T>
{ }

public interface IEntity
{ }

public class TestEntity : IEntity
{ }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top