c# - 如何在带有约束的泛型类中实现非泛型接口

时间:2016-09-12 02:44:51

标签: c# generics interface implements

这是我的代码:

public interface ICar
{
    CarModel Property { get; set; }
    CarModel Method();
}

public Car<T> : ICar where T : CarModel 
{
    T Property { get; set; }
    T Method()
    {
        //Do Stuff
    }
}

我在我的Car<T>类中使用泛型约束实现了接口,但是它没有编译时出现以下错误:

Compilation error (line 18, col 15): 'Car<T>' does not implement interface member 'ICar.Property'. 'Car<T>.Property' cannot implement 'ICar.Property' because it does not have the matching return type of 'CarModel'.
Compilation error (line 18, col 15): 'Car<T>' does not implement interface member 'ICar.Method()'. 'Car<T>.Method()' cannot implement 'ICar.Method()' because it does not have the matching return type of 'CarModel'.

我还需要非通用接口,这里是.Net小提琴:https://dotnetfiddle.net/m1jDnB

我唯一能解决的问题是用实现接口的东西包装属性或方法,但我不想这样做。即:

public Car<T> : ICar where T : CarModel 
{
    T Property { get; set; }
    T Method()
    {
        //Do Stuff
    }

    CarModel ICar.Property 
    { 
      get {return Property; }
      set {Property = (CarModel)value; }
    }

    CarModel ICar.Method()
    {
        return (CarModel)Method();
    }
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

这不可能。如果编译器允许您这样做,结果将不是类型安全的。如果允许类型以您想要的方式编译,则编译器将允许此代码。

public class CarModel {
    public string Name { get; set; }
}

public class Toyota : CarModel {
    public string SpecialToyotaNumber { get; set; }
}

public class Honda : CarModel { }

public interface ICar {
    CarModel Property { get; set; }
    CarModel Method();
}

public class Car<T> : ICar where T : CarModel {
    public T Property { get; set; }

    public T Method() {
        return (T)new CarModel();
    }
}

public class Main {
    public void Run() {
        ICar car = new Car<Toyota>();
        car.Property = new Honda(); // the concrete property is declared Toyota
    }
}