문제

Can someone please break down what a delegate is into a simple, short and terse explanation that encompasses both the purpose and general benefits? I've tried to wrap my head around this and it's just not sinking in.

도움이 되었습니까?

해결책

단일 웹 부분은 공급자와 소비자가 될 수 있습니까?예

Postback없이 웹 파트 연결을 수행 할 수 있습니까?일종의.UpdatePanels를 사용하여 부분 페이지 포스트 백 을 수행 할 수 있습니다.

웹 파트 연결을 체인 할 수 있습니까?나는 그렇게 생각하지 않는다.내가 아는 한 연결을 처리 해야하는 순서를 나타내는 방법이 없습니다.이 예에서는 웹 파트 매니저가 A. 에서 필요로하는 값을 수신하기 전에 B를 데이터로 요청할 수 있습니다.

다른 팁

I have a function:

public long GiveMeTwoTimesTwo()
{
    return 2 * 2;
}

This function sucks. What if I want 3 * 3?

public long GiveMeThreeTimesThree()
{
    return 3 * 3;
}

Too much typing. I'm lazy!

public long SquareOf(int n)
{
    return n * n;
}

My SquareOf function doesn't care what n is. It will operate properly for any n passed in. It doesn't know exactly what number n is, but it does know that n is an integer. You can't pass "Haha not an integer" into SquareOf.

Here's another function:

public void DoSomethingRad()
{
    int x = 4;
    long y = SquareOf(x);
    Console.WriteLine(y);
}

Contrary to its name, DoSomethingRad doesn't actually do anything rad. However, it does write the SquareOf(4) which is 16. Can we change it to be less boring?

public void DoSomethingRad(int numberToSquare)
{
    long y = SquareOf(numberToSquare);
    Console.WriteLine(y);
}

DoSomethingRad is clearly still pretty fail. But at least now we can pass in a number to square, so it won't write 16 every time. (It'll write 1, or 4, or 9, or 16, or... zzzz still kinda boring).

It'd be nice if there was a way to change what happens to the number passed in. Maybe we don't want to square it; maybe we want to cube it, or subtract it from 69 (number chosen at random from my head).

On further inspection, it seems as though the only part of SquareOf that DoSomethingRad cares about is that we can give it an integer (numberToSquare) and that it gives us a long (because we put its return value in y and y is a long).

public long CubeOf(int n)
{
    return n * n * n;
}

public void DoSomethingLeet(int numberToSquare)
{
    long y = CubeOf(numberToSquare);
    Console.WriteLine(y);
}

See how similar DoSomethingLeet is to DoSomethingRad? If only there was a way to pass in behavior (DoX()) instead of just data (int n)...

So now if we want to write a square of a number, we can DoSomethingRad and if we want to write the cube of a number, we can DoSomethingLeet. So if we want to write the number subtracted from 69, do we have to make another method, DoSomethingCool? No, because that takes too damn much typing (and more importantly, it hinders our ability to alter interesting behavior by changing only one aspect of our program).

So we arrive at:

public long Radlicious(int doSomethingToMe, Func<int, long> doSomething)
{
    long y = doSomething(doSomethingToMe);
    Console.WriteLine(y);
}

We can call this method by writing this:

Radlicious(77, SquareOf);

Func<int, long> is a special kind of delegate. It stores behavior that accepts integers and spits out longs. We're not sure what the method it points to is going to do with any given integer we pass; all we know is that, whatever happens, we are going to get a long back.

We don't have to give any parameters to SquareOf because Func<int, long> describes behavior, not data. Calling Radlicious(77, SquareOf) just gives Radlicious the general behavior of SquareOf ("I take a number and return its square"), not what SquareOf will do to any specific integer.

Now if you have understood what I am saying, then you have already one-upped me, for I myself don't really get this stuff.

* END ANSWER, BEGIN WANDERING IDIOCY *

I mean, it seems like ints could be perceived as just really boring behavior:

static int Nine()
{
    return 9;
}

That said, the line between what is data and behavior appears to blur, with what is normally perceived as data is simply boring-ass behavior.

Of course, one could imagine super "interesting" behavior, that takes all sorts of abstract parameters, but requires a ton of information to be able to call it. What if it required us to provide the source code that it would compile and run for us?

Well, then our abstraction seems to have gotten us all the way back to square one. We have behavior so abstract it requires the entire source code of our program to determine what it's going to do. This is fully indeterminate behavior: the function can do anything, but it has to be provided with everything to determine what it does. On the other hand, fully determinate behavior, such as Nine(), doesn't need any additional information, but can't do anything other than return 9.

So what? I don't know.

A delegate is a pointer to a method. You can then use your delegate as a parameter of other methods.

here is a link to a simple tutorial.

The question I had was 'So, why would I want to do that?' You won't really 'get it' until you solve a programming problem with them.

새 복사본을 업로드하는 대신 SharePoint에서 문서를 편집합니다. 이는 메타 데이터를 덮어 씁니다.

A delegate instance is a reference to a method. The reason they are useful is that you can create a delegate that is tied to a particular method on a particular instance of a type. The delegate instance allows you to invoke that method on that particular instance even if the object on which you will invoke the method has left your lexical scope.

The most common use for delegate instances like this is to support the concept of callbacks at the language level.

It simply references a method. They come in great use with working with cross threading.

Here is an example right out of my code.

 //Start our advertisiment thread
    rotator = new Thread(initRotate);
    rotator.Priority = ThreadPriority.Lowest;
    rotator.Start();

    #region Ad Rotation
    private delegate void ad();
    private void initRotate()
    {
        ad ad = new ad(adHelper);
        while (true)
        {
            this.Invoke(ad);
            Thread.Sleep(30000);
        }

    }

    private void adHelper()
    {
        List<string> tmp = Lobby.AdRotator.RotateAd();
        picBanner.ImageLocation = @tmp[0].ToString();
        picBanner.Tag = tmp[1].ToString();            
    }
    #endregion

If you didnt use a delegate you wouldn't be able to crossthread and call the Lobby.AdRotator function.

다른 제안 사항 외에도 페이지가 다시로드되면 변경 사항이 지속되지 않습니다.

In the most basic terms, a delegate is just a variable that contains (a reference to) a function. Delegates are useful because they allow you to pass a function around as a variable without any concern for "where" the function actually came from.

It's important to note, of course, that the function isn't being copied when it's being bundled up in a variable; it's just being bound by reference. For example:

class Foo
{
    public string Bar
    {
        get;
        set;
    }

    public void Baz()
    {
        Console.WriteLine(Bar);
    }
}

Foo foo = new Foo();
Action someDelegate = foo.Baz;

// Produces "Hello, world".
foo.Bar = "Hello, world";
someDelegate();

In most simplest terms, the responsibility to execute a method is delegated to another object. Say the president of some nation dies and the president of USA is supposed to be present for the funeral with condolences message. If the president of USA is not able to go, he will delegate this responsibility to someone either the vice-president or the secretary of the state.

Same goes in code. A delegate is a type, it is an object which is capable of executing the method.

eg.

Class Person
{
   public string GetPersonName(Person person)
   {
     return person.FirstName + person.LastName;
   }

   //Calling the method without the use of delegate
   public void PrintName()
   {
      Console.WriteLine(GetPersonName(this));
   }

   //using delegate
   //Declare delegate which matches the methods signature
   public delegate string personNameDelegate(Person person);

  public void PrintNameUsingDelegate()
  {
      //instantiate
      personNameDelegate = new personNameDelegate(GetPersonName);

      //invoke
      personNameDelegate(this);
  }

}

The GetPersonName method is called using the delegate object personNameDelegate. Alternatively we can have the PrintNameUsingDelegate method to take a delegate as a parameter.

public void PrintNameUsingDelegate(personNameDelegate pnd, Person person)
{
   pnd(person);
}

The advantage is if someone want to print the name as lastname_firstname, s/he just has to wrap that method in personNameDelegate and pass to this function. No further code change is required.

Delegates are specifically important in

  1. Events
  2. Asynchronous calls
  3. LINQ (as lambda expressions)

If you were going to delegate a task to someone, the delegate would be the person who receives the work.

In programming, it's a reference to the block of code which actually knows how to do something. Often this is a pointer to the function or method which will handle some item.

각 제품에 대해 하나의 BI 센터를 만들 수 있습니다. 관리자가 쉽습니다 (각 제품 세트가 다른 각 제품을 가정하고 있음).

그러나 [BI 구성] [1]은 더 까다 롭습니다 ... 당신이 확인해야 할 것들의 커플.

  1. 제대로 계획
  2. 사용자 라이센스 매핑
  3. 보안 저장소 서비스 만들기
  4. Excel Services, Performance Point 및 Visio
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top