C# 如何对非静态成员函数调用操作



我有以下代码可以工作。 我传入的动作只是指向同一类的静态模因的指针。 (其目的是管理线程以安全地访问正确模式线程上的某些 COM 对象。

但是现在我想将 DoCompute 更改为非静态,并且我想使用与 DoCompute 相同的对象调用 func(也更改为非静态)。

如何获取静态数据,以便处理传入的数据?

 public static void DoCompute(Action func)
    {
      Type type = typeof(Computations);
      AppDomain interopDomain = null;
      if (thread != null)
        thread.Join();
      try
      {
          // Define thread.
          thread = new System.Threading.Thread(() =>
          {
              // Thread specific trycatch.
              try
              {
                  // Create a custom AppDomain to do COM Interop.
                string comp = "Computations";
                  interopDomain = AppDomain.CreateDomain(comp);
    //// THIS LINE:  What if func is a non-static member?
                  func.Invoke();
                  Console.WriteLine();
                  Console.WriteLine("End ");
              }
              catch (System.Exception ex)
              {
                  Console.WriteLine(ex.Message);
              }
          });
          // Important! Set thread apartment state to STA.
          thread.SetApartmentState(System.Threading.ApartmentState.STA);
          // Start the thread.
          thread.Start();
          // Wait for the thead to finish.
          thread.Join();
      }
      catch (System.Exception ex)
      {
          Console.WriteLine(ex.Message);
      }
      finally
      {
          if (interopDomain != null)
          {
              // Unload the Interop AppDomain. This will automatically free up any COM references.
              AppDomain.Unload(interopDomain);
          }
      }
  }

您只需从两者中删除static关键字即可。在后台,当您将实例方法传递到 Action 参数时,该实例将作为不可见的第一个参数传递。如果将静态方法传递到 Action 参数中,则不会发生这种情况。您唯一不能做的是从静态方法将非静态方法传递到参数中。

也许使用一些代码会更清楚:

public class TestClass
{
    private string _text;
    private void DoCompute(Action func)
    {
        func.Invoke();
    }
    private static void DoComputeStatic(Action func)
    {
        func.Invoke();
    }
    private static void StaticFunc()
    {
        Console.WriteLine("Static func");
    }
    private void NonstaticFunc()
    {
        Console.WriteLine(_text);
    }
    public void Run()
    {
        _text = "Nonstatic func";
        DoCompute(NonstaticFunc);
        DoComputeStatic(StaticFunc); //Can use static method - instance is ignored
    }
    public static void RunStatic()
    {
        DoComputeStatic(StaticFunc);
        //DoCompute(NonstaticFunc);  // Cannot use instance method - no instance
    }
    public void RunWithThread()
    {
        Thread thread = new Thread(() =>
        {
            _text = "Nonstatic func";
            DoCompute(NonstaticFunc);
        });
        thread.Start();
        thread.Join();
    }
}

最新更新