简体   繁体   English

c#从项目中的所有类访问数据表(使用属性)

[英]c# Access a DataTable from all classes in project (using properties)

I have an application i've been working on to help teach myself c#.net. 我有一个正在致力于帮助自学c#.net的应用程序。 I've come to the point where i'm starting to use classes to organise my project and save me having to copy / paste code everywhere. 我已经开始使用类来组织我的项目,并省去了在任何地方复制/粘贴代码的麻烦。

On my main form i have a Datalist view which i intend to use as a console for ouputting log entries. 在我的主窗体上,我有一个数据列表视图,我打算将其用作输出日志条目的控制台。

I've made a class called "logger" which has the following: 我制作了一个名为“ logger”的类,该类具有以下内容:

    public DataTable DTLog = new DataTable();

public void BuldDTLog()
        {
            DTLog.Columns.Add("Time");
            DTLog.Columns.Add("Type");
            DTLog.Columns.Add("Level");
            DTLog.Columns.Add("Text");
        }

        public void AppendtoLog(String Level, String Type, String Text)
        {

            DTLog.Rows.Add(DateTime.Now, Level, Type, Text);

        }

I call BuildDtLog() from my frmMain which builds the DataTable I then call AppendtoLog("1", "Info", "This is a test log entry"); 我从构建数据表的frmMain调用BuildDtLog(),然后调用AppendtoLog(“ 1”,“ Info”,“ This is a test log entry”); from a button on frmMain and the entry is added to the datatable. 单击frmMain上的按钮,该条目将添加到数据表中。

My problem is when i come to add an entry to the datatable from another class. 我的问题是当我从另一个类向数据表添加条目时。 I get "Object reference not set to an instance of an object" in AppendtoLog. 我在AppendtoLog中收到“对象引用未设置为对象的实例”。 - As if the datatable doesn't exist anymore? -好像数据表不再存在了吗?

I've looked at properties, i've run through a couple of examples and kind of understand how they work and that they could help me in this situation but i'm really struggling to understand how to implement it into my situation. 我研究了属性,通过几个示例进行了研究,并了解了它们的工作方式,并且它们可以在这种情况下为我提供帮助,但是我真的很难理解如何将其实现到我的情况中。 Could someone help? 有人可以帮忙吗?

Thanks 谢谢

make your log class and its functions static and call that function from any class 使您的日志类及其功能静态,并从任何类中调用该功能

public static logger
{
 public DataTable DTLog = new DataTable();

public static void BuldDTLog()
        {
            DTLog.Columns.Add("Time");
            DTLog.Columns.Add("Type");
            DTLog.Columns.Add("Level");
            DTLog.Columns.Add("Text");
        }

        public static void AppendtoLog(String Level, String Type, String Text)
        {

            DTLog.Rows.Add(DateTime.Now, Level, Type, Text);

        }
}

public class otherClass
{
logger.BuldDTLog();
logger.AppendtoLog(param1,param2,param3);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM