[英]Generic return types from abstract/virtual methods
我有兩個基類之間的關系:
public abstract class RecruiterBase<T>
{
// Properties declare here
// Constructors declared here
public abstract IQueryable<T> GetCandidates();
}
public abstract class CandidateBase<T>
{
// Properties declare here
// Constructors declared here
}
他們的具體實現如下:
public class CandidateA : CandidateBase<CandidateA>
{
// Constructors declared here
}
public class RecruiterA : RecruiterBase<RecruiterA>
{
// Constructors declared here
// ----HERE IS WHERE I AM BREAKING DOWN----
public override IQueryable<CandidateA> GetCandidates()
{
return from c in db.Candidates
where c.RecruiterId == this.RecruiterId
select new CandidateA
{
CandidateId = c.CandidateId,
CandidateName = c.CandidateName,
RecruiterId = c.RecruiterId
};
}
}
每個MSDN文檔http://msdn.microsoft.com/en-us/library/ms379564%28VS.80%29.aspx (大約一半)和一個類似的(但不完全相同)的questoin在SO上指定返回類型根據子類從基類中抽象的方法
我可以將我的concreate實現用於我重寫的方法GetCandidates的返回類型,但這不是我想要的,我想利用不同抽象類的具體實現。 這是父/子數據庫關系。 我想要達到的目標是什么? 我目前得到一個編譯時錯誤,我的GetCandidates返回類型不匹配。
謝謝
看起來您需要定義多個泛型類型,其中一個可能被約束為派生自CandidateBase。
嘗試這樣的事情:
public abstract class RecruiterBase<T, C> where C : CandidateBase
{
// Properties declare here
// Constructors declared here
public abstract IQueryable<C> GetCandidates();
}
public abstract class CandidateBase<T>
{
// Properties declare here
// Constructors declared here
}
public class CandidateA : CandidateBase<CandidateA>
{
// Constructors declared here
}
public class RecruiterA : RecruiterBase<RecruiterA, CandidateA>
{
public override IQueryable<CandidateA> GetCandidates()
{
return from c in db.Candidates
where c.RecruiterId == this.RecruiterId
select new CandidateA
{
CandidateId = c.CandidateId,
CandidateName = c.CandidateName,
RecruiterId = c.RecruiterId
};
}
}
編輯包含克里斯的更正
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.