2012-03-28 6 views
0

私は動的メソッドを取る別のファイルのクラスにメソッドを持っています。セットアップの交渉にいくつかの困難があります。どんな助けもありがとう、ありがとう!例えばクラス/ファイル間でデリゲートメソッドを渡す

...

ファイル#1:

class DoSomethingClass 
{ 
    // define delegate 
    public delegate void DelegateMethod(); 

    public void Main() 
    { 
     DelegateMethod d = Func1;  
     AnotherClass.CallsDynamicMethod("Test1", d); 

     d = Func2; 
     AnotherClass.CallsDynamicMethod("Test2", d); 

     // will this work? 
     // AnotherClass.CallsDynamicMethod("Test3", DoSomethingClass.instance.Func3); 
    } 


    // candidate methods for delegation 
    void Func1() 
    { Console.WriteLine("calling Func1"); } 

    void Func2() 
    { Console.WriteLine("calling Func2"); } 

    public void Func3() 
    { Console.WriteLine("calling Func3"); } 
}  


ファイル#2:

class AnotherClass 
{ 
    public static void CallsDynamicMethod(string words, DelegateMethod dynamicMethod) 
    { 
     Console.WriteLine("this is a " + words + " to call..."); 
     dynamicMethod(); 
    } 
} 
+0

何Iあなたが直面する問題は? – gideon

+0

コメントしてください。パラメータとして 'Func3'を渡すだけです。 –

+0

私はファイル間の通信に問題があると思います。私は、DelegateMethodが定義されるように、「DoSomethingClass.DelegateMethod」をFile2のシグネチャに追加する必要があるかもしれないと信じています。このベストプラクティスが何であるかはっきりしていません...コードはちょうどモックアップでした。それが実際に動作するかどうか、csc haha​​と一緒に結び付ける方法を知ってください – user1229895

答えて

2

・ホープこれはあなたの問題を答える

class Program 
{ 
    static void Method() 
    { 
     Console.WriteLine("Method"); 
    } 

    static void Main(string[] args) 
    { 
     Action a = Method; 

     MyClass.SomeMethod(a); 
     MyClass.SomeMethod(Method); 

     Console.ReadLine(); 
    } 
} 

class MyClass 
{ 
    public static void SomeMethod(Action del) 
    { 
     del(); 
    } 
} 
+0

それは動作します、ありがとう! Actionクラスについて知りませんでした。 私はまた、 'using System;またはSystem.Action – user1229895

+0

ああ、行動とFunc を学んでください。その非常に必要不可欠な – Zenwalker

関連する問題