简体   繁体   English

接口中的函数,该函数返回实现该类的对象的类型

[英]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.

相关问题 创建实现Interface的每种类型的对象 - Creating object of each type which implements Interface 具有通用类型的基类,该基类实现具有通用类型的接口 - Base class with a generic type which implements an interface with a generic type 在实现具有对象类型属性的接口的类中更改属性类型 - Changing property type in class that implements interface with object type property 取实现接口的类 - Take class which implements interface 如何传递给实现certan接口的泛型函数类类型? - How to pass to a generic function class type that implements certan interface? 接口方法返回类型是实现接口的类 - Interface method return type to be class that implements the interface 从它实现的接口创建 class 的实例 - Create Instance of a class from interface which it implements 在引用其实现的接口时,对象会存在吗? - Will an object live while there is reference to interface which It implements? 设置实现接口的类的所有成员来自接口类型的对象,而不需要在C#中编写大量代码 - Set all members of class that implements an interface from an object of the interface type without a lot of writing code in C# 创建实现给定接口的对象的实例 - Creating instance of an object which implements a given interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM