【问题标题】:Generic method using Linq and inheritance to bind to object使用 Linq 和继承绑定到对象的通用方法
【发布时间】:2012-06-26 14:27:27
【问题描述】:

我正在努力弄清楚如何执行以下操作:

我有几种方法可以返回不同的强类型 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();
}

【问题讨论】:

  • 使用string.Equals(x, y, StringComparison.CurrentCultureIgnoreCase) 进行不区分大小写的比较。 ToLower 比较最终会失败。

标签: c# linq c#-4.0


【解决方案1】:

您可以使用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();
}

【讨论】:

    【解决方案2】:

    如下改变你的方法

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

    【讨论】:

    • 我知道我错过了什么!谢谢
    • 在绑定由 Linq 的延迟性质导致的结果 IEnumerable 时,我也遇到了空引用异常。这已通过将 ToList() 放在查询末尾来解决。
    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2012-05-23
    • 2013-11-09
    相关资源
    最近更新 更多