【问题标题】:Using “OfType” in LINQ在 LINQ 中使用“OfType”
【发布时间】:2012-07-02 12:29:49
【问题描述】:

我有两个派生自 BankAccount 类的类——FixedBankAccount 和 SavingsBankAccount。这是基于使用 LINQ to SQL 的“TPH(按层次结构表)”工作的。

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
[InheritanceMapping(Code = "Fixed", Type = typeof(FixedBankAccount), IsDefault = true)]
[InheritanceMapping(Code = "Savings", Type = typeof(SavingsBankAccount))]
public abstract partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged

我需要实现一个 GetAllAccountsOfType 方法,它将返回所有 SavingsBankAccount(如果传递的类型是 SavingsBankAccount)或 FixedBankAccounts(如果传递的类型是 FixedBankAccount)。我收到错误:

找不到类型或命名空间名称“param””

使用以下代码(在 LINQ 查询中使用“OfType”)

我们怎样才能让它发挥作用?

存储库:

namespace RepositoryLayer
{    
    public class LijosSimpleBankRepository : ILijosBankRepository
    {
        public System.Data.Linq.DataContext Context { get; set; }

        public virtual List<DBML_Project.BankAccount> GetAllAccountsOfType(DBML_Project.BankAccount param)
        {
            var query = from p in Context.GetTable<DBML_Project.BankAccount>().OfType<param>()
                        select p;
        }
    }
}

【问题讨论】:

标签: c# .net linq linq-to-sql generics


【解决方案1】:

声明:

public IEnumerable<T> GetAllAccounts<T>()
    where T : BankAccount // T must inherit class BankAccount, like your two sub-classes do
{
    return Context.GetTable<DBML_Project.BankAccount>().OfType<T>();
}

用法:

var allSaving = GetAllAccounts<SavingsBankAccount>();
var allFixed = GetAllAccounts<FixedBankAccount>();

【讨论】:

  • 谢谢..现在我明白了“泛型”的概念。当所有“类型”的逻辑都相同时使用泛型..
  • 我推荐了msdn.microsoft.com/en-in/library/twcad0zb(v=vs.80).aspx 以了解更多关于泛型的信息。但它并没有告诉我们可以使用泛型方法的适当位置。有没有像Use generic methods when the logic is same for all "types"这样强调点的好文章?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
相关资源
最近更新 更多