从函数中声明全局变量?

时间:2011-04-15 14:27:53

标签: c# global-variables

这是我的代码:

    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.
    }

正如你所看到的,服务器对象(srv)是用connect()函数声明的,当然我需要这个对象是全局的,所以我可以从其他函数访问它,比如也像sendMsg一样。

您认为最好的方法是什么?

谢谢!

4 个答案:

答案 0 :(得分:1)

您需要将其设为实例变量。

public class Foo
{
  private string instanceVariable;


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

注意:如果将变量暴露给外部,请使用“属性”。

答案 1 :(得分:1)

将其声明为成员变量(它不需要是全局的...)您是否正在尝试处理某些问题,这会让您不想采用这种方法?

答案 2 :(得分:1)

我的偏好是使用私有的setter创建一个延迟加载的属性。在这种情况下,这意味着您必须对创建srv的cf对象执行相同的操作。

答案 3 :(得分:1)

为此类问题做的最好的事情是创建一个包含静态成员的类,以便您可以设置并从中获取值。通过这种方式,您可以从班级可以看到的任何地方访问它,使其“全球化”。像这样:

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

您可以选择实现自定义get和sets以防止出现问题或将对象创建为类的静态构造函数的一部分。