繁体   English   中英

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

[英]c# - How to implement a non generic interface in a generic class with constraints

这是我的代码:

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

我对此的唯一解决方法是使用实​​现接口的东西包装属性或方法,但我不想这样做。 IE:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM