2016-10-23 4 views
0

안녕하세요 저는 프로그래밍을 처음 사용합니다. 기본적으로 클래스 A의 메서드 A를 클래스 B의 메서드 내부에서 클래스 B의 변수 A에 저장해야하지만 방법을 찾을 수없는 것 같습니다. 급변수에 메소드를 저장하는 방법은 무엇입니까?

public void methodA() 
{ 
*method* 
} 

클래스 B

Delegate variableA; //I believe using Delegate is wrong 

public void methodB(); 
{ 
variableA = ClassA.methodA(); 
} 

그러면 클래스 B에 저장된 방법 변수를 이용하는 것이다 다른 방법이있을 것이다 :

는 예를 제공한다.

public void methodC(); 
{ 
variableA; 
} 

이것은 정확한 코드가 아니지만 기본적으로 그 요지입니다. 어떤 도움을 주신 것입니다 :)

편집 : 도와 주셔서 감사합니다 모두!

+0

사용'의회 처리 예를 들어, –

+1

'Action'과'Func' 델리게이트를 사용하여 메소드를 저장할 수 있습니다. –

답변

1

ClassA 정의 :

public class ClassA 
{ 
    public void MethodA() 
    { 
     Console.WriteLine("Hello World!"); 
    } 
} 

ClassB 정의 :

,143 여기
0

사용 반사 :

public class A 
{ 
    public void MethodA() 
    { 
     Console.WriteLine("MethodA"); 
    } 

    public static void StaticMethodA() 
    { 
     Console.WriteLine("StaticMethodA"); 
    } 
} 

public class B 
{ 
    MethodInfo mv = typeof(A).GetMethod("MethodA"); 
    MethodInfo smv = typeof(A).GetMethod("StaticMethodA"); 

    public void CheckA(bool useStatic) 
    { 
     if (useStatic) smv.Invoke(null, null); 
     else mv.Invoke(new A(), null); 
    } 
} 

class MainClass 
{ 
    [STAThread] 
    public static void Main(string[] args) 
    { 
     var b = new B(); 
     b.CheckA(true); 
     b.CheckA(false); 
    } 
} 

은 MSDN에서 details를 참조하십시오.

public class Test 
    { 
     private Action<int> hiddenMethod = new Action<int>((i) => 
     { 
      Console.WriteLine(i); 
     }); 

     public void PublicMethod(int i) 
     { 
      hiddenMethod(i); 
     } 
    } 

하고 사용 :

class Program 
{ 
    static void Main(string[] args) 
    { 
     Test t = new Test(); 
     t.PublicMethod(21); 
     Console.Read(); 
    } 
} 
0

은 일례이며 (210)

Program 정의 :

static void Main(string[] args) 
{ 
    ClassA classA = new ClassA(); 
    ClassB classB = new ClassB(); 
    classB.MethodB(classA); 
    classB.MethodC(); 
    Console.ReadLine(); 
} 
관련 문제