在 C# 中使用自定义数据模型实现泛型和扩展可观察集合方法



我的 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

首先,您应该添加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);

最新更新