2013-06-08 2 views
1

호출하는 메서드의 이름을 가져올 수 있으며 그 결과를 기반으로 코드를 실행할 수 있습니까?조건부 문의 조건으로 호출 메서드 이름 사용

아래에는 데이터베이스 CRUD 작업에 사용되는 두 가지 방법이 있습니다. 하나는 데이터베이스에 객체를 추가하고 다른 것은 업데이트합니다. 둘 다 조작에 대한 통계 보고서가 들어있는 오브젝트를 리턴합니다.

특정 조건에서 Update 메소드 내에서 stat 객체를 반환하는 경우 작업 메소드의 pkey 필드를 업데이트하지 않아도됩니다.

public OperationStat Add(object obj) 
{ 
    // Contains operation status data. 
    OperationStat op = new OperationStat(); 
    op.PrimaryKey = pkey.newkey(); 

    // Record to update 
    Person pete = new Person(); 

    // call update method. 
    op = this.Update(pete); 
} 

public OperationStat Update(object obj) 
{ 
    OperationStat op = new OperationStat(); 
    string callmethod = "Add"; 

    // Get stacktrace. 
    StackTrace stackTrace = new StackTrace(); 
    StackFrame stackFrame = stackTrace.GetFrame(1); 
    MethodBase methodBase = stackFrame.GetMethod(); 

    if(methodBase.Name != callmethod) 
    { 
    // create new primary key for status. 
    op.Primarykey = pkey.newkey(); 
    } 

    // fill operation stat object with details 
    return op; 
} 
+1

호출자가 완벽 [스택에서] 최적화 할 수 있으므로 당신은 스택 추적에 의존해서는 안 (http://stackoverflow.com/a/6597522/276994). – Vlad

+1

코드를 읽으면 왜 내가 "Add"를 Update() 인수로 전달하지 않는지 궁금합니다 ... –

답변

4

.NET 4.5에는 이러한 종류의 정보를 제공하는 몇 가지 새로운 특성이 도입되었습니다.

CallerMethodNameAttribute

:

는 메소드의 호출자의 메서드 또는 속성 이름을 얻을 수 있습니다.


public OperationStat Update(object obj, [CallerMethodName] string calledFrom = "") 
{ 
    OperationStat op = new OperationStat(); 
    string callmethod = "Add"; 

    if(calledFrom != callmethod) 
    { 
    op.Primarykey = pkey.newkey(); 
    } 

    return op; 
} 
+0

나는 당신을 사랑합니다. – Klue

+0

.Net 4.0 환경을위한 솔루션? – Klue

+0

@Klue - 스택 트레이스와 프레임을 가지고있는 것처럼 ... – Oded

관련 문제