Nice programing

대표자들을 이해하려는 것이 우주의 본질을 이해하려고하는 것처럼 느껴지는 이유는 무엇입니까?

nicepro 2021. 1. 8. 22:52
반응형

대표자들을 이해하려는 것이 우주의 본질을 이해하려고하는 것처럼 느껴지는 이유는 무엇입니까?


저는 두 권의 책을 읽었습니다. 그들은 여전히 ​​나에게 전혀 의미가 없습니다. 델리게이트를 사용하는 코드를 작성할 수 있지만 그 이유를 모르겠습니다. 이 문제가있는 유일한 사람입니까, 아니면 그냥 바보입니까? 누군가 내가 언제, 어디서, 왜 실제로 대리인을 사용하는지 설명해 주시면 영원히 사랑할 것입니다.


대리자는 변수에서 함수를 전달하는 방법 일뿐입니다.

콜백을 수행하기 위해 위임 된 함수를 전달합니다. 예를 들어 비동기 IO를 수행 할 때 디스크에서 데이터를 읽을 때 호출되는 위임 함수 (델리게이트 매개 변수로 작성한 함수)를 전달합니다.


다른 사람들이 언급했듯이 대리인은 콜백에 편리합니다. 그들은 다른 많은 것들에도 유용합니다. 예를 들어, 최근에 작업 한 게임에서 총알이 맞았을 때 다른 일을합니다 (일부는 피해를 입히고, 일부는 실제로 맞은 사람의 건강을 높이고, 일부는 피해를 입히지 않고 대상을 독살하는 등). 이를 수행하는 고전적인 OOP 방법은 기본 총알 클래스와 많은 하위 클래스입니다.

Bullet
    DamageBullet
    HealBullet
    PoisonBullet
    DoSomethingElseBullet
    PoisonAndThenHealBullet
    FooAndBarBullet
    ....

이 패턴을 사용하면 총알에 새로운 동작을 원할 때마다 새 하위 클래스를 정의해야합니다. 이는 엉망이고 많은 중복 코드로 이어집니다. 대신 대표자들과 함께 해결했습니다. 총알에는 총알이 개체에 부딪 힐 때 호출되는 OnHit 델리게이트가 있으며, 물론 원하는대로 델리게이트를 만들 수 있습니다. 이제 이렇게 총알을 만들 수 있습니다.

new Bullet(DamageDelegate)

분명히 일을하는 훨씬 더 좋은 방법입니다.

함수형 언어에서는 이런 종류의 것을 더 많이 보는 경향이 있습니다.


델리게이트는 머신의 메모리에서 특정 메서드가있는 위치를 아는 간단한 컨테이너입니다.

모든 델리게이트에는 Invoke(...)메서드가 있으므로 누군가가 델리게이트를 갖고 있으면 실제로 그 메서드가 무엇을하는지 알거나 귀찮게하지 않고도 실제로 실행할 수 있습니다.

이것은 특히 디커플링에 유용합니다. GUI 프레임 워크는 이러한 개념 없이는 불가능할 것입니다. Button왜냐하면는 사용할 프로그램에 대해 알 수 없기 때문에 클릭 할 때마다 자체적으로 메서드를 호출 할 수 없기 때문입니다. 대신 클릭 할 때 호출해야하는 메서드를 지정해야합니다.

나는 당신이 이벤트에 익숙하고 정기적으로 사용한다고 생각합니다. event필드는 실제로 (또한 멀티 캐스트 대리자를 호출) 대의원의 목록입니다. event키워드 가없고 (멀티 캐스트가 아닌) 대리자 만 있는 경우 C #에서 이벤트를 "시뮬레이션"할 수있는 방법을 살펴보면 상황이 더 명확해질 것입니다 .

public class Button : Rectangle
{
    private List<Delegate> _delegatesToNotifyForClick = new List<Delegate>();

    public void PleaseNotifyMeWhenClicked(Delegate d)
    {
        this._delegatesToNotifyForClick.Add(d);
    }

    // ...

    protected void GuiEngineToldMeSomeoneClickedMouseButtonInsideOfMyRectangle()
    {
        foreach (Delegate d in this._delegatesToNotifyForClick)
        {
            d.Invoke(this, this._someArgument);
        }
    }
}

// Then use that button in your form

public class MyForm : Form
{
    public MyForm()
    {
        Button myButton = new Button();
        myButton.PleaseNotifyMeWhenClicked(new Delegate(this.ShowMessage));
    }

    private void ShowMessage()
    {
        MessageBox.Show("I know that the button was clicked! :))))");
    }
 }

내가 조금 도울 수 있기를 바랍니다. ;-)


도움이 될 수 있습니다.

  • 대리자는 형식 (메서드 서명 정의)입니다.
  • 대리자 인스턴스는 메서드에 대한 참조 (일명 함수 포인터)입니다.
  • 콜백은 델리게이트 유형의 매개 변수입니다.
  • 이벤트는 델리게이트 유형의 (종류) 속성입니다.

The purpose of delegates is that you can have variables/fields/parameters/properties(events) that 'hold' a function. That lets you store/pass a specific function you select runtime. Without it, every function call has to be fixed at compile time.

The syntax involving delegates (or events) can be a bit daunting at first, this has 2 reasons:

  1. simple pointer-to-functions like in C/C++ would not be type-safe, in .NET the compiler actually generates a class around it, and then tries to hide that as much as possible.

  2. delegates are the corner-stone of LINQ, and there is a steep evolution from the specify-everything in C#1 through anonymous methods (C#2) to lambdas (C#3).

Just get acquainted with 1 or 2 standard patterns.


Come on Guys! All of you successfully complicated the DELEGATES :)!

I will try to leave a hint here : i understood delegates once I realized jquery ajax calls in Javascript. for ex: ajax.send(url, data, successcallback, failcallback) is the signature of the function. as you know, it sends data to the server URL, as a response, It might be 200OK or some other error. In case of any such event(success/fail), you want to execute a function. So, this acts like a placeholder of a function, to be able to mention in either success or failure. That placeholder may not be very generic - it might accept a set of parameters and may/may not return value. That declaration of such Placeholder, if done in C# IS CALLED DELEGATE! As javascript functions not strict with number of arguments, you would just see them as GENERIC placeholders...but C# has some STRICT declarations... that boils down to DELEGATE declarations!!

Hope it helps!


Delegate is a type safe function pointer, meaning delegate points to a function when you invoke the delegate function the actual function will be invoked. It is mainly used when developing core application framework. When we want to decouple logic then we can use delegate. Ie instead of hand coding logic in a particular method we can pass the delegate to the function and set different function logic inside the delegate function. Delegates adds flexibility to your framework.

Example: how to use it

class program {
 public static void Main) {
  List<Employee> empList = new List<Employee> () {
   new Employee () {Name = "Test1", Experience = 6 },
   new Employee () {Name = "Test2", Experience = 2 },
  }

// delegate point to the actual function
IsPromotable isEligibleToPromote = new IsPromotable(IsEligibleToPromoteEmployee)
Employee emp = new Employee();

// pass the delegate to a method where the delegate will be invoked.
emp.PromoteEmployee(empList, isEligibleToPromote);

// same can be achieved using lambda empression no need to declare delegate 
emp.PromoteEmployee (empList, emply =>emply.Experience > 2);

   // this condition can change at calling end 
   public static bool IsEligibleToPromoteEmployee (emp){
      if (emp.Experience > 5)
       return true;
      else
      return false;
    }
  }
}


public delegate bool IsPromotable(Employee emp);

public class Employee  {
  public string Name {get; set;}
  public int Experience {get; set;}

  // conditions changes it can 5, 6 years to promote
  public void PromoteEmployee (List<Employee> employees, IsPromotable isEligibleToPromote) {
  foreach (var employee in employees) {
    // invoke actual function
    if (isEligibleToPromote(employee)){
       Console.WriteLine("Promoted");   
    }
  }
}

ReferenceURL : https://stackoverflow.com/questions/2678632/why-does-trying-to-understand-delegates-feel-like-trying-to-understand-the-natur

반응형