简体   繁体   中英

Cannot return concrete implementation of constraint generic

I have some problem around generics and I don't see my mistake.

Given this code:

public interface IMyInterface { }

public class MyImplementation : IMyInterface { }

public interface IMyFactory<T> where T : class, IMyInterface
{
    T Create();
}

public class MyFactory<T> : IMyFactory<T> where T : class, IMyInterface
{
    public T Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation(); // <--- red squigglies - Cannot implicitly convert type 'ConsoleApp18.MyImplementation' to 'T'
    }
}

If I use it like this return new MyImplementation() as T; it works. No more errors are present.

If I use it like this return (T)new MyImplementation(); i get a code suggestion to remove the unnecessary cast. (Yeah that's what I think too, why is it not possible to return the concrete implementation since it is compatible with T?) and also the first error (Cannot implicitly convert...) is still present.

So why do I get this error and what is the correct implementation to return my concrete implementation?

I have some problem around generics and I don't see my mistake.

Your mistake is to use generics. Given the code you shown, you don't need them at all. The factory should return a IMyInterface instead of T .

public interface IMyFactory
{
    IMyInterface Create();
}

public class MyFactory : IMyFactory
{
    public IMyInterface Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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