如何在具有约束的泛型类中实现非泛型接口

本文关键字:泛型类 实现 泛型接口 约束 | 更新日期: 2023-09-27 18:06:46

下面是我的代码:

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();
    }
}

有更好的方法吗?

如何在具有约束的泛型类中实现非泛型接口

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

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
    }
}