开发者

declaring global variables from within a function?

开发者 https://www.devze.com 2023-02-26 02:26 出处:网络
Here\'s my code: private void connect() { try { textBox1.Text += \"connecting... \\r\\n\"; button1.Enabled = false;

Here's my code:

    private void connect()
    {
        try
        {
            textBox1.Text += "connecting... \r\n";
            button1.Enabled = false;

            DuplexChannelFactory<IfaceClient2Server> cf =
                    new DuplexChannelFactory<IfaceClient2Server>(
                        new CallbackImpl(),
                        new NetTcpBinding(),
                        new EndpointAddress("net.tcp://localhost:9080/service"));

            IfaceClient2Server srv = cf.CreateChannel();
            srv.StartConnection(name); /// need to make this one global!
            textBox1.Text += name + "connected!\r\n"; 
        }
        catch
        {
           开发者_运维百科 button1.Enabled = true;
            textBox1.Text += "error connecting!\r\n";
        }
    }


    private void sendMsg()
    {
        srv.Message_Cleint2Server("Hello!");
        /// srv doesn't exist here.
    }

as you can see, the server object ( srv ) is being declared from with the connect() function, yet of course I need this object to be global, so that I would be able to access it from other functions, such as sendMsg as well.

What do you think might be the best way to do this?

Thanks!


The best thing to do for this type of problem is to create a class that contains static members so you can set and get the values from it. This way you can access it from everywhere that the class can be see making it "global". Like this:

public class ApplicationController
{
    public static IfaceClient2Server Server { get; set; }
}

You may choose to implement custom get and sets to prevent issues or create the object as a part of the static constructor of the class.


You need to make it an instance variable.

public class Foo
{
  private string instanceVariable;


  public void Set(string s)
  {
    instanceVariable = s;
  }
  public string Get()
  {
    return instanceVariable; //same value as "s" in "Set"
  }
}

Note: If exposing variables to the outside, use Properties.


Declare it as a member variable (it doesn't need to be global...) Is there some issue you're trying to deal with that makes you not want to take that approach?


My preference is to make a lazy-loaded property with a private setter. In this context, that would mean you would have to do the same thing with your cf object that creates the srv.

0

精彩评论

暂无评论...
验证码 换一张
取 消