[英]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.