[英]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. 我有两个结构:Dog和Cat,它们都属于IAnimal。
IAnimal has a function ConvertFrom(IAnimal) which converts any object that inherits from IAnimal into the same type as called the function. IAnimal具有一个功能ConvertFrom(IAnimal),它将从IAnimal继承的任何对象转换为与该函数相同的类型。
Eg: 例如:
I call Dog.ConvertFrom(cat) and I get a dog with the fields mapped over from cat. 我叫Dog.ConvertFrom(cat),然后得到一条狗,其中的字段是从cat映射过来的。
I call Cat.ConvertFrom(dog) and I get a cat with the fields mapped over from dog. 我叫Cat.ConvertFrom(dog),然后得到一只猫,其中的字段是从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). 但我宁愿指定它以狗或猫的形式返回,而不是以IAnimal的形式出现(从而减轻了进一步的投放)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.