使动态对象全局化

时间:2013-04-11 17:12:08

标签: c#

我的原始代码:

public partial class LineInstance
{
   EventWaitHandle _stopHandle;
   Private int _linenumber;
   // many variable;
   public LineInstance(int linenumber, EventWaitHandle stopper)
   {
      _stopHandle = stopper;
  _linenumber = linenumber;
      // blah
   }    

   private string Menu()
   {
      dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
  var reply = api.GetId(Id: "888");
  var response1 = reply.Response;
  // blah blah
}
 }

现在我想制作这些

dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
var reply = api.GetId(Id: "888");
var response1 = reply.Response;

是全局因为我想在这个类的其他方法中使用。我尝试将它们移到类构造函数

之前的区域

更新

public partial class LineInstance
{
EventWaitHandle _stopHandle;
private int _linenumber;
dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
var reply = api.GetId(Id: "888");
var response1 = reply.Response;
          // blah blah

但是我收到了一个错误:

  

错误:“非静态字段,方法或属性

需要对象引用

如何修改我的代码以使其成为全局代码?

2 个答案:

答案 0 :(得分:1)

如果您想要在没有任何特定的班级实例的情况下使用它,请将对象定义为static

public partial class LineInstance
{
private static dynamic api;
EventWaitHandle _stopHandle;
private int _linenumber;
    // many variable;
public LineInstance(int linenumber, EventWaitHandle stopper)
{
_stopHandle = stopper;
_linenumber = linenumber;
    // blah
 }  

您应该提供public property来访问对象

public static dynamic Api{
 get{ return api; }

}

除此之外,global中没有C#个变量,您应该以任何方式避免它们!

答案 1 :(得分:0)

要从课程的其他方法中添加这些属性,您不必将它们设置为静态。您的更新代码几乎是正确的。以下是您需要做的事情:

public partial class LineInstance
{
   EventWaitHandle _stopHandle;
   Private int _linenumber;
   dynamic api;
   dynamic reply;
   dynamic response1;

   // many variable;
   public LineInstance(int linenumber, EventWaitHandle stopper)
   {
      _stopHandle = stopper;
  _linenumber = linenumber;
      // blah
   }    

   private string Menu()
   {
  api = new Http("http://80.56.16.214/MyServices/MyData.svc");
  reply = api.GetId(Id: "888");
  response1 = reply.Response;
  // blah blah
  }
 }

如您所见,我唯一改变的是初始化构造函数中的字段,而不是类体 - 这样就没有错误。