简体   繁体   中英

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

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.

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

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

This is based on the assumption that your implementation of ComponentsEventView will allow for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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