从静态类触发非静态类? [英] Triggering a non-static class from a static class?

查看:155
本文介绍了从静态类触发非静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class nonStaticDLLCLASS 
{
public event Event1;

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

class StaticTestClass
{
public static GoStaticMethod()
{
//这里我要启动event1在nonStaticDLLCLASS
//我知道以下行是不正确的,但我可以做这样的事情吗?

(nonStaticDLLCLASS)StaticTestClass.ObjectThatCalledMe.Event1();

}
}

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

解决方案

实例方法只能在实例上调用。在您的示例中,实例正在调用静态方法。你可以给静态方法一个参数,让实例传递给自己的引用吗?这样的东西:

  class nonStaticDLLCLASS 
{
public event Event1;

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

class StaticTestClass
{
public static GoStaticMethod(nonStaticDLLCLASS instance)
{
//这里我想在非StaticDLLCLASS
中触发Event1 //我知道以下行是不正确的,但我可以这样做吗?

instance.Event1();

}
}

我想你需要澄清你的问题是为什么你不能这样做,或为什么实例不能提出自己的事件。


I am writing a class library(API) in C#. The class is non-static and contains several public events. Is it possible to trigger those events from a static method in a separate class? For example...

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

   }
}

I know you typically have to create an instance of the non-static class in order to access it's methods but in this case an instance has already been created, just not by the class that is trying to access it.

解决方案

Instance methods can only be called on instances. In your example, the instance is calling the static method. Can you give the static method a parameter allowing the instance to pass in a reference to itself? Something like this:

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

   }
}

I think you need to clarify your question to specify why you can't do something like this, or why the instance can't raise its own event.

这篇关于从静态类触发非静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆