【问题标题】:Inheritance - target specific inherited class C#继承 - 目标特定的继承类 C#
【发布时间】:2016-12-05 09:03:18
【问题描述】:

我有多重继承,看看下面的示例评论,以更好地了解我想要做什么。

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&lt;&gt; 继承的类?

【问题讨论】:

    标签: c# inheritance base-class


    【解决方案1】:

    我不会使用泛型,而是使用接口。正如另一个答案所表明的那样,基类无法知道哪个类继承自它,因此恕我直言,泛型不是这里的解决方案。

    需要注意的一点是,您正在从基类构造函数调用派生类代码,这很危险,因为派生对象尚未完全创建。

    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) { ... }
    }
    

    【讨论】:

    • 谢谢你的想法,但在这种情况下 MapFromSourceObject(object source) 将有一个空的主体,整个想法是有一个通用函数,它将映射视图和基本模型类一次继承自 BaseViewModelFor.
    【解决方案2】:

    不幸的是,基类不知道从它继承了哪个类。一种选择是调用基本构造函数,然后在 ComponentsEventView 构造函数中调用 MapFromSourceObject

    public ComponentsEventView(...) : base(...)
    {
       this.MapFromSourceObject(source)
    }
    

    这是基于您的 ComponentsEventView 实现将允许这样做的假设。

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 2015-12-09
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      相关资源
      最近更新 更多