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();
}
4

2 回答 2

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();
}
于 2012-06-25T10:31:51.047 回答
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();
}
于 2012-06-25T10:29:06.770 回答