2012-08-01 162 views
0

我有一個類heirarсhy派生類的實例:擴展方法,它返回

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using MyProject.Models; 
using MyProject.Extensions; 

namespace MyProject.Models 
{ 
    public abstract class Vehicle 
    { 
     public string Color { get; set; } 
    } 

    public class Car : Vehicle 
    { 
     public int Mileage { get; set; } 
    } 

    public class Boat : Vehicle 
    { 
     public int Displacement { get; set; } 
    } 

} 


namespace MyProject.Extensions 
{ 
    public static class VehicleExtensions 
    { 
     public static IEnumerable<Vehicle> FilterByColor(this IEnumerable<Vehicle> source, string color) 
     { 
      return source.Where(q => q.Color == color); 
     } 
    } 
} 

namespace MyProject.Controllers 
{ 
    public class IndexController : Controller 
    { 
     public ActionResult Index() 
     { 
      List<Car> cars = new List<Car>(); 
      cars.Add(new Car() { Color = "white", Mileage = 10000 }); 
      cars.Add(new Car() { Color = "black", Mileage = 20000 }); 

      IEnumerable<Car> filtered = cars.FilterByColor("black");   
       // Compile error, can not cast IEnumerable<Vehicle> to IEnumerable<Car> 

       //.OfType<Car>() - only this helps. I`m looking for another ways 

      return View(filtered); 
     } 
    } 
} 

我想在IEnumerable<Car>使用的擴展方法,並從中獲得IEnumerable<Car>但方法返回IEnumerable<Vehicle>,因爲它的工作原理在所有派生類 - 編譯錯誤。我只知道解決這個問題的方法之一是添加電話.OfType<Car>(),但這是一種首選方式嗎?可能有更好的方法嗎?

回答

5

我懷疑你只是想使其與約束的一般方法,以確保該類型參數爲Vehicle或子類:

public static IEnumerable<T> FilterByColor<T>(this IEnumerable<T> source, 
    string color) where T : Vehicle 
{ 
    return source.Where(q => q.Color == color); 
} 
+0

非常感謝你。 – Roman 2012-08-01 18:24:31

3

你需要使它通用:

public static IEnumerable<T> FilterByColor(this IEnumerable<T> source, string color) where T : Vehicle 
+0

非常感謝。 – Roman 2012-08-01 18:25:13

+0

只是語法上的一個小錯誤 - 應該是FilterByColor ,否則「where」不起作用。 – Roman 2012-08-01 18:47:54