2012-06-25 70 views
2

我努力让我的头围绕如何做到以下几点:通用方法绑定到对象

我有几个方法,返回不同的强类型的IEnumerable对象。 这些强类型的类共享公共基类,该基类公开了我想要在Linq选择器中访问的属性。

但是,我似乎无法得到这个工作。如果我只是在方法中传递基类型,那么绑定IEnumerable时会出错,因为派生类中可用的属性不可用。

如果我尝试传递类型,那么因为Linq表达式不知道类型,我不能访问我在我的Linq表达式中需要的属性。

我需要以某种方式告诉Linq表达式,我的IEnumerable类型是从我的基类派生的。 下面是什么,我试图做一个例子:

private IEnumerable<MyStronglyTypedResultSet> GetReportDetails() 
{ 
    // this returns the IEnumerable of the derived type 
} 

public class MyBaseClass 
{ 
    public Guid UserId {get; set;} 
    public string OfficeName {get; set;} 
} 

public class MyStronglyTypedResultSet : MyBaseClass 
{ 
    public string FullName {get; set;} 
    public int Age {get; set;} 
} 

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; // This needs to have access to the properties in 'MyStronglyTypedResultSet' 
    MyUsefulObject.DataaBind(); 
} 
+1

使用'string.Equals(x,y,StringComparison.CurrentCultureIgnoreCase)'进行大小写不敏感的比较。 ToLower比较最终会失败。 – adrianm

回答

1

改变你的方法如下面

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) where T : MyBaseClass 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; // This needs to have access to the properties in 'MyStronglyTypedResultSet' 
    MyUsefulObject.DataaBind(); 
} 
+0

我知道我错过了一些东西!谢谢 –

+0

当绑定由Linq的延迟性质引起的IEnumerable时,我也得到一个空引用异常。这通过在查询结尾处放置ToList()来解决。 –

2

可以使用OfType扩展方法。

public void MyProblemMethod<T>(IEnumerable<T> allData, string officeToFind) 
{ 
    // How do I tell Linq that my <T> type is derived from 'MyBaseClass' so I can access the 'OfficeName' property? 

    IEnumerable<T> myData = allData.OfType<MyBaseClass>.Where(c => c.OfficeName .ToLower().Equals(officeToFind.ToLower())); 
    MyUsefulObject.DataSource= myData; 
    MyUsefulObject.DataaBind(); 
} 
+0

这也工作谢谢 –