[英]Inheritance - target specific inherited class C#
我有多個繼承,請看下面的示例注釋,以更好地了解我要執行的操作。
CompanyEventsView : BaseViewModelFor<CompanyEvents>
{
}
BaseViewModelFor<TSource> : BaseViewModel where TSource : class
{
public BaseViewModelFor(IAggregator aggregator, IRepository<TSource> repository, int i)
{
Aggregator = aggregator;
var source = repository.GetKey(i);
(this as CompanyEventsView).MapFromSourceObject(source); // (this as CompanyEventsView) how could I make this generic so if I inherit another class to point to it
}
}
所以我想知道的是如何強制( this as CompanyEventsView
)位,以便它始終指向從BaseViewModelFor<>
繼承的類?
我不會使用泛型,而是使用接口。 另一個答案表明,基類無法知道哪個類繼承自它,因此IMHO泛型不是此處的解決方案。
要注意的一件事是您正在從基類構造函數調用派生類代碼,這很危險,因為派生對象尚未完全創建。
public interface IFromSourceObjectMapper {
void MapFromSourceObject(object source); // TODO: Update parameter type
}
BaseViewModelFor<TSource> : BaseViewModel where TSource : class
{
public BaseViewModelFor(IAggregator aggregator, IRepository<TSource> repository, int i)
{
Aggregator = aggregator;
var source = repository.GetKey(i);
var mapper = this as IFromSourceObjectMapper;
if (mapper != null) {
(this as CompanyEventsView).MapFromSourceObject(source); // (this as CompanyEventsView) how could I make this generic so if I inherit another class to point to it
}
}
}
CompanyEventsView : BaseViewModelFor<CompanyEvents>, IFromSourceObjectMapper
{
public void MapFromSourceObject(object source) { ... }
}
不幸的是,基類無法知道從其繼承的類。 一種選擇是調用基本構造函數,然后調用ComponentsEventView構造函數中的MapFromSourceObject
public ComponentsEventView(...) : base(...)
{
this.MapFromSourceObject(source)
}
這是基於一個假設,即您的ComponentsEventView實現將允許這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.