如何重写List.Add方法? [英] How to override List.Add method?

查看:549
本文介绍了如何重写List.Add方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个错误记录类,如下所示:

Currently I have a error logging class like so:

public class Log
{
    public enum LogTypes
    {
        Info = 1,
        Error = 2,
        Warning = 3
    }


    public string Message { get; set; }
    public LogTypes LogType { get; set; }


    public Log(string Message, LogTypes LogType)
    {
        this.Message = Message;
        this.LogType = LogType;
    }

我有一个用于新列表的初始化程序:

I have this initialiser for a new list:

List<Log> LogList = new List<Log>();

如何使用LogList.Add(Message, LogType)代替LogList.Add(new Log(Message, LogType));?

我知道这是一个很小的变化,但是我仍在学习C#并且很好奇.谢谢!

I know it is a minor change but I am still learning C# and am curious. Thanks!

推荐答案

首先,我不会这样做.这不是使用List<Log>的任何人所期望的.与其公开一个普通的List<Log>,不如考虑创建一个Logger类或类似的类,其中包含 一个List<Log>并公开一个Log(string message, LogType type)方法,但实际上并未公开List<Log>

Firstly, I wouldn't do this. It's not what anyone using a List<Log> would expect. Rather than exposing a plain List<Log>, consider creating a Logger class or something similar which contains a List<Log> and exposes a Log(string message, LogType type) method, but doesn't actually expose the List<Log>.

如果您真的希望能够直接在列表中呼叫Add(message, type),则有两种选择:

If you really want to be able to call Add(message, type) directly on the list, there are two options:

  • 创建一个从List<Log>派生的新类:

public LogList : List<Log>
{
    public void Add(string message, LogType type)
    {
        Add(new Log(message, type));
    }
}

请注意,这是重载(添加新方法签名,但名称相同,为Add),而不是 overrideing (为现有签名方法提供新行为)用于virtual方法)-您需要创建LogList而不是List<Log>的实例:

Note that this is overloading (adding a new method signature but with the same name, Add), not overriding (providing new behaviour for an existing signature method for a virtual method) - and you'll need to create an instance of LogList rather than List<Log>:

LogList list = new LogList();
list.Add(message, type);

  • List<Log>添加扩展方法,这将有效地将该方法添加至所有 List<Log>实例.

  • Add an extension method to List<Log>, which will effectively add that method to all List<Log> instances.

    public static LogListExtensions
    {
        public static void Add(this Log<List> list, string message, LogType type)
        {
            list.Add(new Log(message, type));
        }
    }
    

  • 顺便说一句,我可能还会从您的Log类型中删除设置器-为什么构造后需要更改消息或类型?

    As an aside, I'd probably also remove the setters from your Log type - why would you need to be able to change the message or type after construction?

    这篇关于如何重写List.Add方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆