繁体   English   中英

继承-目标特定的继承类C#

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM