2009-12-22 128 views
0

我正在用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(); 

    } 
} 

我知道你通常要访问它的方法,但在这种情况下,一个实例已经创建,只是没有通过类来创建非静态类的实例即试图访问它。

回答

3

实例方法只能在实例调用。在你的例子中,实例正在调用静态方法。你可以给静态方法一个参数,允许实例传递给自己的引用吗?事情是这样的:

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

    } 
} 

我想你需要澄清你的问题,指定为什么你不能做这样的事情,为什么实例不能提高自己的事件。

+0

这使得一吨的感觉。我认为我的大脑不能正常工作! – PICyourBrain 2009-12-22 17:35:39

4

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

为了达到此目的,您必须将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); 
    } 
}