简体   繁体   中英

Function in an Interface which returns an object of the type of whatever class implements it

This is probably best described with an example.

I have two structs: Dog and Cat, which both belong to IAnimal.

IAnimal has a function ConvertFrom(IAnimal) which converts any object that inherits from IAnimal into the same type as called the function.

Eg:

I call Dog.ConvertFrom(cat) and I get a dog with the fields mapped over from cat.

I call Cat.ConvertFrom(dog) and I get a cat with the fields mapped over from dog.

Is there any way to do this with interfaces? Specify that the function must return the same type as the class that implements the function?

I thought of simply writing it as:

IAnimal ConvertFrom(IAnimal)

but I'd rather be able to specify that it's coming back as a dog, or a cat, instead of as IAnimal (and thus mitigating a further cast).

You may be talking about something like the Curiously Recurring Template Pattern to achieve static polymorphism. You could use generics to have:

public interface IAnimal

public interface IAnimal<T> : IAnimal where T : IAnimal<T>

public class Dog : IAnimal<Dog>

public class Cat : IAnimal<Cat>

Then your method becomes something like:

T ConvertFrom(IAnimal someAnimal)

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