简体   繁体   English

C#如何在非静态成员函数上调用Action?

[英]C# How do I invoke an Action on a non-static member function?

I have the following code which works. 我有以下代码可行。 I pass in Actions which are just pointers to static memebers of this same class. 我传入的动作只是指向同一类静态成员的指针。 (Its purpose is to manage threading to safely access some COM objects on the rightly moded thread.) (其目的是管理线程以安全地访问正确模式线程上的某些COM对象。)

But now I want to change DoCompute to non-static, and I want to Invoke func (also changed to non-static) with the same object that DoCompute has. 但是现在我想将DoCompute更改为非静态,并且我希望使用与DoCompute相同的对象来调用func(也更改为非静态)。

How do I get the static out, so there's passed-in data to work on? 如何获得静态输出,所以有传入的数据可以使用?

 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 try\catch.
              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);
          }
      }
  }

You just remove the static keywords from both. 您只需从两者中删除static关键字。 Under the hood, when you pass an instance method into the Action parameter, the instance is passed along as an invisible first parameter. 在引擎盖下,当您将实例方法传递给Action参数时,实例将作为不可见的第一个参数传递。 If you pass a static method into the Action parameter, that does not happen. 如果将静态方法传递给Action参数,则不会发生这种情况。 The only thing you cannot do is pass a non-static method into the paramater from a static method. 你唯一不能做的是从静态方法将非静态方法传递给参数。

Perhaps this will be clearer with some code: 有些代码可能会更清楚:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何引用不同类C#的非静态成员 - How do I reference a non-static member of a different class c# 如何从 C# 中的静态方法调用非静态方法? - How do I call a non-static method from a static method in C#? 在C#中编写静态和非静态方法时,如何避免出现“调用不明确……”错误? - How do I avoid 'call is ambiguous…' error when writing static and non-static methods in C#? C#“非静态字段需要对象引用”,静态成员函数的类问题 - C# “An object reference is required for the non-static field,” Class issue with Static Member Function C#无法访问外部类型的非静态成员 - C# cannot access a non-static member of outer type C#中相同功能的静态和非静态版本 - Static and non-static version of the same function in C# 非静态事物是否来自静态C#? - Do Non-Static things from Static, C#? C ++ Interop:如何从本机C ++调用C#类,这个类是非静态的? - C++ Interop: How do I call a C# class from native C++, with the twist the class is non-static? c#如何从action中访问一个非静态的公共变量 - c# how access a non-static public variable from action static 事件与 C# 中的非静态事件相比如何? - How do static events compare to non-static events in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM