简体   繁体   中英

Abstract collection of base class

I'm creating an WPF application using the MVVM framework.

I've got several classes all inheriting from a base class "MessageParentBase"

public class ChatMessage : MessageParentBase
{
}

public class CargoMessage : MessageParentBase
{
}

The ViewModels all inherit once again from a base class "ParentMessageWindowBaseViewModel"

public class UserControlChatViewModel : ParentMessageWindowBaseViewModel
{
}

public class UserControlCargoViewModel : ParentMessageWindowBaseViewModel
{
}

Now what I want to do is have an observable collection in my "ParentMessageWindowBaseViewModel" class

abstract internal ObservableCollection<MessageParentBase> GridData
{
    get; set;
}

Which is there so I can have a generic method at the "ParentMessageWindowBaseViewModel" level, but at the child classes I want to have a more specific collection declared

internal override ObservableCollection<ChatMessage > GridData
{
    get { return _GridData; }
    set
    {
        _GridData = value;
    }
}

Visual studio is telling me it must be declared as a type of "MessageParentBase".

Can someone please explain to me how I can achieve this as I'm struggling at the moment.

Many thanks for your help.

A ObservableCollection< ChatMessage> isn't the same as ObservableCollection< MessageParentBase> so you can't override it.

You could use this like this:

public class MessageParentBase
{
}

public class ChatMessage : MessageParentBase
{
}

public abstract class ParentMessageWindowBaseViewModel<T> where T : MessageParentBase
{
    abstract internal ObservableCollection<T> GridData
    {
        get;
        set;
    }
}

public class Child : ParentMessageWindowBaseViewModel<ChatMessage>
{

    internal override ObservableCollection<ChatMessage> GridData
    {
        get;
        set;
    }
}

But storing all Childs in 1 list isn't possible. So it won't fix the issue with inheritance on a generic property.

In the class where you declare the property GridData to be abstract , why do you also introduce a backing field _GridData there? Don't do that.

If you want the property to be abstract , do not put any supporting field there. If you want to implement the property at the "high" level (base class), remove the abstract modifier from it.

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