0

这可能是一个简单的问题,但是到目前为止我找不到解决方案...

假设我有一个接口“IEntity”,它由其他几个接口实现。我想要的是这些接口中的每一个都实现了一个具有自身返回类型的方法。例如,实体“Car”应该返回“ICar”,而实体“Person”应该返回“IPerson”。我尝试使用泛型类型实现此功能,但没有找到真正可接受的解决方案。

希望你能帮助我,在此先感谢。

4

4 回答 4

1

通常的方法是使用“循环模板模式”:

interface IEntity<T> where T : IEntity<T>
{
    T GetSelf();
}

然后你的实体类型实现这个接口,使用它们自己的类型作为泛型参数T

public class Car : IEntity<Car>
{
    Car GetSelf() { return this; }
}
于 2013-03-03T13:50:19.350 回答
1

我并不完全清楚你在追求什么,但这听起来很接近而且很简单。

interface IEntity<T>
{
    T Value { get; }
}

class Car : IEntity<ICar>
{
    ICar Value { get; }
}

class Person : IEntity<IPerson>
{
    IPerson Value { get; }
}

你需要更复杂的东西吗?

于 2013-03-03T13:50:27.647 回答
1

好吧,您可以使用泛型相当容易地做到这一点,但我假设您的代码在某个地方会处理一个IEntity并且在编译时不知道底层泛型类型。如果是这样,那么您可以这样声明两个接口:

public interface IEntity<T> : IEntity
{
    new T GetThis();
}

public interface IEntity
{
    object GetThis();
}

然后你Car可能看起来像这样:

public class Car : ICar, IEntity<ICar>
{
    public ICar GetThis()
    {
        Console.WriteLine("Generic GetThis called");
        return this;
    }

    object IEntity.GetThis()
    {
        Console.WriteLine("Non-generic GetThis called");
        return this;
    }
}

这使用Explicit Interface Implementation,因此如果调用代码知道它是 a Car(或者更确切地说是 an IEntity<ICar>),那么它将利用通用版本。如果它只知道它,IEntity那么它将利用非通用版本。

所以一些可能会利用这一点的代码:

public static T SomeMethod<T>(IEntity<T> entity)
{
    T target = entity.GetThis(); //Generic GetThis called
    return target;
}

public static object SomeNonGenericMethod(IEntity entity)
{
    object target = entity.GetThis(); //Non-generic GetThis called
    return target;
}

Car car = new Car();
ICar icar = SomeMethod<ICar>(car);

IEntity someEntity = new Car();
object obj = SomeNonGenericMethod(someEntity);
于 2013-03-03T13:51:16.807 回答
0

只需为 cause 中的方法添加一个返回类型,它是派生接口中的方法返回的所有可能类型的超类。对于您的情况:

interface IEntity {
  IEntity SomeMethod();
}
于 2013-03-03T13:52:49.163 回答