简体   繁体   English

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

[英]Inheritance - target specific inherited class C#

I've got multiple inheritance, have a look at the example comment bellow to get a better understanding of what I am trying to do. 我有多个继承,请看下面的示例注释,以更好地了解我要执行的操作。

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
    }
}

So what I would like to know is how to force ( this as CompanyEventsView ) bit so it's always pointing to the class that is inherited from BaseViewModelFor<> ? 所以我想知道的是如何强制( this as CompanyEventsView )位,以便它始终指向从BaseViewModelFor<>继承的类?

I would not use a generic, but use an interface. 我不会使用泛型,而是使用接口。 As a different answer indicates, the base class cannot know which class inherits from it, so IMHO generics isn't the solution here. 另一个答案表明,基类无法知道哪个类继承自它,因此IMHO泛型不是此处的解决方案。

One thing to watch out for is that you are calling derived-class-code from base-class-constructor, which is dangerous, since the derived object is not created fully yet. 要注意的一件事是您正在从基类构造函数调用派生类代码,这很危险,因为派生对象尚未完全创建。

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

Unfortunately the base class can't know which class inherited from it. 不幸的是,基类无法知道从其继承的类。 One option is to call the base constructor and then MapFromSourceObject in the ComponentsEventView constructor 一种选择是调用基本构造函数,然后调用ComponentsEventView构造函数中的MapFromSourceObject

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

This is based on the assumption that your implementation of ComponentsEventView will allow for this. 这是基于一个假设,即您的ComponentsEventView实现将允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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