2012-06-29 4 views
1

태그가있는 경우 .NET이 아닌 Mono와 협력하고 있습니다.델리게이트 정의 - 인/아웃 방법으로 어떤 차이가 있습니까?

대리인을 사용할 때 범위에 대한 모범 사례가 혼동 스럽습니다. 이 예에서 autoOrientationsautoRotationSetups외부의 Awake() 외부에서 클래스의 다른 위치에서 사용됩니다.

List<ScreenOrientation> autoOrientations; 
Dictionary<ScreenOrientation, Action> autoRotationSetups; 

void Awake() { 
    var verticalOrientations = new List<ScreenOrientation>(
     new []{ScreenOrientation.Portrait, ScreenOrientation.PortraitUpsideDown}); 
    Action setAutoRotationsToVertical =() => { 
     // I don't think this defintion is important for this question, 
     // but it does use the just-defined List. 
    }; 
    var horizontalOrientations = new List<ScreenOrientation>(
     new []{ScreenOrientation.LandscapeLeft, ScreenOrientation.LandscapeRight}); 
    Action setAutoRotationsToHorizontal =() => {// See last comment. 
    }; 
    autoRotationSetups = new Dictionary<ScreenOrientation, Action>() { 
     {ScreenOrientation.Portrait, setAutoRotationsToVertical}, 
     {ScreenOrientation.PortraitUpsideDown, setAutoRotationsToVertical}, 
     {ScreenOrientation.LandscapeLeft, setAutoRotationsToHorizontal}, 
     {ScreenOrientation.LandscapeRight, setAutoRotationsToHorizontal}, 
    }; //... 

또는 I 클래스의 메소드를 정의하고 대표에 할당 할 수있다 : 또한 Unity를 사용하는 경우, 자주 use Awake() where you might otherwise be using a constructor 있습니다. 그 변경은 다음과 같이 보일 것입니다 :

List<ScreenOrientation> verticalOrientations, horizontalOrientations; 
void SetAutoRotationsToVertical() {} 
void SetAutoRotationsToHorizontal() {} 

void Awake() { 
    Action setAutoRotationsToVertical = SetAutoRotationsToVertical; 
    Action setAutoRotationsToHorizontal = SetAutoRotationsToHorizontal; //... 

두 가지 접근법 간에는 어떤 변화가 있습니까? 현재의 지식 수준에서는 잘못된 기억 영역에 사는 변수에 대해 주로 염려합니다. The Truth About Value Types은 그 점을 분명히 할 수 있습니다. 나는 분명히하고 있다고 생각합니다.하지만 아직 완전히 확신 할 수는 없습니다. 또한, 나는 어떤 길로가는 다른 가능한 이유를 알지 못한다. 그러므로이 질문을한다.

사람들이 주관적이라고 생각해서 최근에 질문을 받고 있습니다. 수용 가능한 대답이 될 것입니다. "예"는 단순한 문체 선택이 아니라는 설명을 추가로 요구할 것입니다.

답변

3

두 가지 접근 방식 사이에 어떤 변화가 있습니까?

람다 식을 통해 익명 메서드를 만들면 컴파일러에서 대신 메서드를 만듭니다. 현실적으로이 두 버전은 거의 차이가 없을 것입니다.

가장 큰 차이점은 컴파일러가 익명 ​​메서드를 만들도록 허용하면 Awake() 메서드 내에서 로컬로 정의 된 변수 주변의 클로저를 사용할 수 있다는 것입니다. 변수를 보유하기 위해 잠재적으로 여분의 클래스가 생성 될 수 있기 때문에 이것은 원하는 것이 무엇이든지에 따라 좋은 것 또는 나쁜 것일 수 있습니다. 이 같은 아니에요 "바로 거기에있다 -

내 현재의 지식 수준에서

, 나는

내가 너무 이것에 대해 걱정하지 것이다 메모리의 잘못된 지역에 사는 변수에 대한 대부분의 걱정 "그리고"잘못된 "기억 영역 ...

+0

고마워! 클로저에 대한 언급은 나를 도왔으며, 많은 도움이되었습니다. http://diditwith.net/PermaLink,guid,235646ae-3476-4893-899d-105e4d48c25b.aspx – Jessy

+2

@Jessy 첫 번째 옵션은 꼭 닫아야 할 것입니다. 익명 메소드 밖에서 정의 된 변수를 사용하는 경우에만 발생합니다. 당신이 모든 것을 지역적으로 유지한다면 (즉, "정상적인 방법"과 동일합니다),이 둘은 효과적으로 동일 할 것입니다. –

관련 문제