[英]Call class from another Project C#
I really need your help and to figure this out. 我真的需要您的帮助,并弄清楚这一点。
My Project: 我的项目:
AccessProjectMap -- MainClass.cs -- ErrorLog.cs (public) ThreadProjectMap -- StartThread.cs
I'd like to make StartThread
my default project when the project starts. 我想在项目启动时将
StartThread
我的默认项目。 Now I need the ErrorLog.cs file in my ThreadProjectMap. 现在,我的ThreadProjectMap中需要ErrorLog.cs文件。 I made a reference and I can actually say
ErrorLog log = new ErrorLog();
我做了一个参考,我实际上可以说
ErrorLog log = new ErrorLog();
which does also work. 这也有效。 When I try to use the ErrorLog in
MainClass.cs
it's working too. 当我尝试在
MainClass.cs
使用ErrorLog时,它也正在工作。
However I cannot use log
inside the main or DoThreading function. 但是我不能在main或DoThreading函数中使用
log
。
class StartThread {
static string threadRefresh = ConfigurationManager.AppSettings.Get("refreshTime").ToString();
Access ac = new Access();
ErrorLog log = new ErrorLog();
static void Main(String[] args) {
log.LogMessageToFile("== Start Main() ==");
Thread t = new Thread(new ThreadStart(DoThreading));
t.Start();
Console.Read();
}
static void DoThreading() {
int refresh = 1;
while (true) {
Console.WriteLine("Test");
log.LogMessageToFile("== Test - inside Thread ==");
Thread.Sleep(1000);
}
}
}
The issue is not because of different projects/namespaces, instead you are trying to access an instance member in a static method . 问题不是由于不同的项目/命名空间,而是您试图以静态方法访问实例成员 。
Make your log
field static
and it should compile fine. 将您的
log
字段设置为static
,并且应该可以正常编译。
static ErrorLog log = new ErrorLog(); //Here, make it static
static void Main(String[] args) {
log.LogMessageToFile("== Start Main() ==");
Thread t = new Thread(new ThreadStart(DoThreading));
t.Start();
Console.Read();
}
The instance you create of ErrorLog on this line: 您在此行上创建的ErrorLog实例:
ErrorLog log = new ErrorLog();
Is an instance variable. 是实例变量。 The
Main
and DoThreading
methods are static. Main
和DoThreading
方法是静态的。
You have two options: Either make the ErrorLog static as well, like so: 您有两个选择:也可以将ErrorLog设置为静态,如下所示:
static ErrorLog log = new ErrorLog();
Or, just instantiate it inside your static methods. 或者,只需在您的静态方法中实例化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.