简体   繁体   中英

How can I return a class instance with a generic type as an interface with a generic type?

When I have a simple Class and Interface, I can do this:

public class Foo : IFoo
{
    public IFoo Instance()
    {
        return this;
    }
}

Is there a way to do the same thing when both are generics?

public class Base<T, TI>
{
    public TI Instance()
    {
        return this; // Nope
        return (T) this; // Nope
    }
}

public class Foo : Base<Foo, IFoo>
{

}

However I try to do this, I'm getting a "cannot implicitly convert type" error.

C# does not support this.

The best you can do is

public class Base<T, TI> where T : Base<T, TI>, TI
{
    public TI Instance()
    {
        return (TI) (object) this; // Yep
    }
}

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