在 C# 中使用自定义数据模型实现通用和扩展 ObservableCollection 方法

Implementing generic and extension ObservableCollection method with custom data model in C#

我的 MVVM 应用程序中有一个模型 class MessageModel,它包含以下构造函数:

public class MessageModel
{
        // Private fields here 

        public MessageModel()
        {
        }

        public MessageModel(MessageType msgType, DateTime dateTime, string strSource, string strText)
        {
            this._type = msgType;
            this._dateTime = dateTime;
            this._source = strSource;
            this._text = strText;
        }

        // Public properties here
}

在视图模型中我有以下声明:

ObservableCollection<MessageModel> myMessages = new ObservableCollection<MessageModel>();

现在我需要总是在第一个位置(开始)向这个集合添加项目,所以我这样做:

myMessages.Insert(0, new MessageModel() { 
                             // values here 
                         });

就像我经常做的那样,如果我想像这样为集合实现一个扩展方法(它不会编译):

public static class CollectionExtensions
{
    public static void Insert<T>(this ObservableCollection<T> collection, MessageType messageType, IParticipant sender, string strText)  where T : MessageModel
    {
        collection.Insert(0, new T()
        {
            MessageType = messageType,
            MessageDateTime = DateTime.Now,
            MessageSource = sender.ParticipantName,
            MessageText = strText
        });
    }
}

那我可以做:

myMessages.Insert(messageType, sender, text);

这可能吗?如果是,怎么做?

我正在使用 Visual Studio 2008 和 NET Framework 3.5

首先你应该添加 new() 以允许在你的扩展方法中使用构造函数

public static class CollectionExtensions
{
    public static void Insert<T>(this ObservableCollection<T> collection, MessageType messageType, IParticipant sender, string strText)  where T : MessageModel, new()
    {
        collection.Insert(0, new T()
        {
            MessageType = messageType,
            MessageDateTime = DateTime.Now,
            MessageSource = sender.ParticipantName,
            MessageText = strText
        });
    }
}

那么你应该像这样使用你的扩展方法:

myMessages.Insert<MessageModel>(messageType, sender, text);