从其他实例访问静态对象

时间:2013-08-19 19:23:45

标签: c# static instance

我有Program class,其中包含:

private static ClientBase objClientBase = new ClientBase(new List<RecordType> { RecordType.none }, ModuleType.Monitor);
    static void Main(string[] args)
    {
        objClientBase.Connect(); //IRRELEVANT
        objQueueMon = new Main(); //<-INSIDE THIS IS WHERE I WANT TO ACCESS objClientBase
        objClientBase.MainModuleThreadManualResetEvent.WaitOne(); //IRRELEVANT
    }

如你所见,这个Progam会创建一个Main class实例:

objQueueMon = new Main();

请注意,它们在不同的文件中分开,但Main类实例是在Program类中创建的。

在我的Program类中,我想访问objClientBase

我是否必须创建构造函数方法并将其传递或公开访问它? 所以我想要实现的是,在Main类中,做一个objClientBase.FUNCTION

2 个答案:

答案 0 :(得分:0)

你可以完全按照你刚才所说的做法:

public class Main {

    private ClientBase _caller;

    public Main (ClientBase caller) {
        _caller = caller;
    }

}

或者,您可以稍后再设置

public class Main {

    private ClientBase _caller;

    public Main () {

    }

    // only your assembly sets it
    internal SetClientBase(ClientBase cb) {

        _caller = cb;
    }

    // but anyone gets it
    // Now you can let some client execute "Function"
    public ClientBase Caller {
        {return _caller;} 
    }

}

只是一个例子

答案 1 :(得分:0)

更改Main类的构造函数以接受ClientBase对象,如下所示:

public class Main
{
    private ClientBase _clientBase;

    public Main(ClientBase clientBase)
    {
        _clientBase = clientBase;
    }

    public void SomeMethod()
    {
        // Use ClientBase.FUNCTION here
        _clientBase.FUNCTION();
    }
}