简体   繁体   English

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

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

Here is my code:这是我的代码:

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

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

I have implemented the interface in my Car<T> class with generic constraints but it doesn't compile with the following error:我已经在我的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'.

I also need the interface to be non generic, here is a .Net fiddle: https://dotnetfiddle.net/m1jDnB我还需要非通用的接口,这里是一个 .Net 小提琴: https : //dotnetfiddle.net/m1jDnB

The only work around I have for this is to wrap the property or method with something that implements the interface as it wants it BUT I dont want to do this.我对此的唯一解决方法是使用实​​现接口的东西包装属性或方法,但我不想这样做。 ie: 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();
    }
}

Is there a better way?有没有更好的办法?

This can't be done.这是做不到的。 If the compiler did allow you to do it, the result wouldn't be type safe.如果编译器确实允许您这样做,则结果将不是类型安全的。 If the types were allowed to compile the way you wanted, then this code would be permitted by the compiler.如果允许类型以您想要的方式编译,那么编译器将允许此代码。

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