添加到内部List< string>在新的实例中. [英] Adding to internal List<string> in a new instance.
问题描述
想创建一个List< string>来保存错误消息,但是可以在控制台应用程序的不同类中添加到此消息中.我有一个调用实用程序类的业务层,该实用程序类中引发的错误需要添加 进入错误列表.
Would like to create a List<string> to hold error messages but have the ability to add to this in different classes in my Console application. I have a business layer that calls a utility class, errors raised in the utility class need to be added to the errors list.
这可能吗,还有更好的方法吗?
Is this possible and also is there a better way?
这是一个平凡的例子,展示了我想要达到的目标.
This is a trivialised example to show what I want to acheive.
谢谢
推荐答案
你好您可以通过使Utils类或错误变为静态来实现此目的. 单例模式是实现此目的的常用方法:
You can achieve this by making the Utils class or the errors static. The singleton pattern is a common way to achieve this:
using System; public class Utils { private static Utils instance; private Utils() {} public static Utils Instance { get { if (instance == null) { instance = new Utils(); } return instance; } } private List<string> _errors = new List<string>(); public void AddError(string error) { // TODO: add a lock in case this is multithreaded _errors.Add(error); } }
希望这会有所帮助!
Hope this helps!
这篇关于添加到内部List< string>在新的实例中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!