【问题标题】:Triggering a non-static class from a static class?从静态类触发非静态类?
【发布时间】:2009-12-22 16:36:20
【问题描述】:

我正在用 C# 编写一个类库 (API)。该类是非静态的,并且包含几个公共事件。是否可以从单独的类中的静态方法触发这些事件? 比如……

class nonStaticDLLCLASS
{
   public event Event1;

   public CallStaticMethod()
  {
     StaticTestClass.GoStaticMethod();
  }
}

class StaticTestClass
{
   public static GoStaticMethod()
   {
     // Here I want to fire Event1 in the nonStaticDLLCLASS
     // I know the following line is not correct but can I do something like that?

     (nonStaticDLLCLASS)StaticTestClass.ObjectThatCalledMe.Event1();

   }
}

我知道您通常必须创建非静态类的实例才能访问它的方法,但在这种情况下,已经创建了一个实例,而不是尝试访问它的类。

【问题讨论】:

    标签: c# events static parent-child non-static


    【解决方案1】:

    不,实例成员只能在该类型的有效实例上调用/访问。

    为了使其工作,您必须将nonStaticDLLCLASS 的实例传递给StaticTestClass.GoStaticMethod 并使用该实例引用来调用/访问非静态成员。

    在上面的示例中,您如何指定要访问的类型的实例?静态方法不知道任何实例,那么它如何知道要使用哪个实例,或者是否有任何实例加载到内存中?

    考虑这个例子:

    using System;
    
    class Dog
    {
        public String Name { get; set; }
    }
    
    class Example
    {
        static void Main()
        {
            Dog rex = new Dog { Name="Rex" };
            Dog fluffy = new Dog { Name="Fluffy" };
        }
        static void sayHiToDog()
        {
            // In this static method how can I specify which dog instance
            // I mean to access without a valid instance?  It is impossible since
            // the static method knows nothing about the instances that have been
            // created in the static method above.
        }
        static void sayHiToDog(Dog dog)
        {
            // Now this method would work since I now have an instance of the 
            // Dog type that I can say hi to.
            Console.WriteLine("Hello, " + dog.Name);
        }
    } 
    

    【讨论】:

      【解决方案2】:

      实例方法只能在实例上调用。在您的示例中,该实例正在调用静态方法。你能给静态方法一个参数,允许实例传入对自身的引用吗?像这样的:

      class nonStaticDLLCLASS
      {
         public event Event1;
      
         public CallStaticMethod()
        {
           StaticTestClass.GoStaticMethod(this);
        }
      }
      
      class StaticTestClass
      {
         public static GoStaticMethod(nonStaticDLLCLASS instance)
         {
           // Here I want to fire Event1 in the nonStaticDLLCLASS
           // I know the following line is not correct but can I do something like that?
      
           instance.Event1();
      
         }
      }
      

      我认为你需要澄清你的问题,以说明为什么你不能做这样的事情,或者为什么实例不能引发自己的事件。

      【讨论】:

      • 这很有意义。我认为我的大脑无法正常工作!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多