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

问题描述 投票:0回答:1

我的MVVM应用程序中有一个模型类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

c# wpf mvvm extension-methods observablecollection
1个回答
2
投票

首先,您应该添加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);
© www.soinside.com 2019 - 2024. All rights reserved.