2016-11-05 2 views
-1

함수 대리자를 사용하여 매개 변수 사용하여 메서드를 호출 할 방법을 찾고 있어요.함수 대리자 매개 변수 사용하여 C#

대신 processOperationB를 호출하는 대신 위임 함수를 사용할 수 있습니다. 그러나 아래의 방법이 달성 될 수있는 어떤 방법을 찾고 있습니다.

public class Client 
{ 

    public AOutput OperationA (string param1, string param2) 
    { 
    //Some Operation 
    } 

    public BOutput OperationB(string param1, string param2) 
    { 
     //Some Operation 
    } 
} 


public class Manager 
{ 
    private Client cl; 



    public Manager() 
    { 
     cl=new Client(); 
    } 


    private void processOperationA(string param1, string param2) 
    { 

     var res = cl.OperationA(param1,param2); 
     //... 

    } 

    private void processOperationB(string param1, string param2) 
    { 
     var res = cl.OperationB(param1,param2); 

     // trying to Call using the GetData , in that case I could get rid of individual menthods for processOperationA, processOperationB 

     var res= GetData<BOutput>(x=> x.OperationB(param1,param2)); 
    } 


    // It could have been done using Action, but it should return a value 
    private T GetData<T>(Func<Client,T> delegateMethod) 
    { 

    // how a Function delegate with params can be invoked 
    // Compiler expects the arguments to be passed here. But have already passed all params . 

     delegateMethod(); 


    } 

} 
+2

좋아, 그 코드의 문제점은 무엇입니까? 오류가 있습니까? 어떤 오류입니까? – JLRishe

+0

당신이 무엇을하려고하는지 명확하지 않습니다 ... 코드를 직접 실행할 수있는 것처럼 왜 GetData를 호출 할 것인가 ... – Phil1970

답변

2

귀하의 의견을 읽

컴파일러는 인수가 여기

전달 될 것으로 예상하지만 그건 정말 사실이 아니다. 예, 그것은 논쟁을 기대하지만, 당신이 생각하는 것은 아닙니다.

귀하의 delegateMethod 매개 변수는 유형 Client의 단일 인수를 필요로 의미 및 유형 T의 값을 반환하는 Func<Client, T>입니다. 당신이 보여준 코드를 기반으로, 당신은 대신을 작성해야합니다 : 당신이 해결하기 위해 노력하고 폭 넓은 문제가 무엇인지 나에게 분명하지 않다

private T GetData<T>(Func<Client,T> delegateMethod) 
{ 
    return delegateMethod(cl); 
} 

. 여기에 아무 것도 추가하지 않는 GetData<T>() 메서드가 표시되지 않습니다. 호출자는 각기 적절한 "작업 ..." 메소드를 호출 할 수 있습니다. 즉, 귀하의 processOperationA() 메소드에서와 같이 생각할 수 있습니다.

하지만 적어도 컴파일러 오류를 해결할 수 있습니다. 보다 광범위한 문제에 대한 도움을 원하시면 새로운 질문을 올리십시오. 수행하려는 작업을 명확하게 보여주는 좋은 Minimal, Verifiable, and Complete code example을 포함하고 시도한 것과 작동하지 않는 것을 정확하게 설명하십시오.