我正在努力思考如何执行以下操作:
我有几种返回不同强类型 IEnumerable 对象的方法。 这些强类型类共享一个公共(public)基类,该基类公开我想要在 Linq 选择器中访问的属性。
但是我似乎无法让它工作。如果我只是在方法中传递基类型,那么在绑定(bind) 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();
}
最佳答案
您可以使用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();
}
关于c# - 使用 Linq 和继承绑定(bind)到对象的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11187537/