问题
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>();
How can I use LogList.Add(Message, LogType)
instead of LogList.Add(new Log(Message, LogType));
?
I know it is a minor change but I am still learning C# and am curious. Thanks!
回答1:
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>
.
If you really want to be able to call Add(message, type)
directly on the list, there are two options:
Create a new class derived from
List<Log>
:public LogList : List<Log> { public void Add(string message, LogType type) { Add(new Log(message, type)); } }
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 avirtual
method) - and you'll need to create an instance ofLogList
rather thanList<Log>
:LogList list = new LogList(); list.Add(message, type);
Add an extension method to
List<Log>
, which will effectively add that method to allList<Log>
instances.public static LogListExtensions { public static void Add(this Log<List> list, string message, LogType type) { list.Add(new Log(message, type)); } }
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?
回答2:
You can create your own class derived from List
and define new Add
method for your needs, e.g.:
public class MyListClass : List<Log>
{
public void Add(string message, Log.LogTypes logType)
{
this.Add(new Log(message, logType));
}
}
回答3:
It is not going make any difference apart from saving a second or two of typing. Having said that you can always implement your own list class and use that. Or you could make use of extension methods.
来源:https://stackoverflow.com/questions/22165015/how-to-override-list-add-method