Почему События использования?

Ну, во-первых, этот код представляет собой полный беспорядок, чтобы охотиться.

  1. Вы не завершили ни одного цитируемого раздела (в printf и scanf с)
  2. Нет отступа
  3. Использование double для playerCount [1117 ]
  4. И поскольку это double, его значение может быть чем-то вроде 12.000001 и, следовательно, r может никогда не быть 0.
  5. Я бы предложил использовать getchar вместо scanf, когда вам нужно проанализировать такие символы, как \t, \n и «» (пробел).
  6. Я бы сказал, проверьте этот раздел еще раз: x < lowerbound || x > upperbound, потому что я думаю, что вы намеревались сделать это: x > lowerbound || x < upperbound

Исправьте эти проблемы, и ваш код должен работать нормально, я думаю. Отступ не имеет ничего общего с точностью.

9
задан DaveInCaz 19 February 2019 в 20:46
поделиться

5 ответов

To provide a concrete normal world example....

You have a form, the form has a listbox. There's a nice happy class for the listbox. When the user selects something from the listbox, you want to know, and modify other things on the form.

Without events:

You derive from the listbox, overriding things to make sure that your parent is the form you expect to be on. You override a ListSelected method or something, that manipulates other things on your parent form.

With events: Your form listens for the event to indicate a user selected something, and manipulates other things on the form.

The difference being that in the without events case you've created a single-purpose class, and also one that is tightly bound to the environment it expects to be in. In the with events case, the code that manipulates your form is localized into your form, and the listbox is just, well, a listbox.

10
ответ дан 4 December 2019 в 08:16
поделиться

What would be very useful is a non trivial example of an app which uses events (guess it really helps testing too?)

Thoughts so far are:

Why use Events or publish / subscribe?

Any number of classes can be notified when an event is raised.

The subscribing classes do not need to know how the Metronome (see code below) works, and the Metronome does not need to know what they are going to do in response to the event

The publisher and the subscribers are decoupled by the delegate. This is highly desirable as it makes for more flexible and robust code. The metronome can change how it detects time without breaking any of the subscribing classes. The subscribing classes can change how they respond to time changes without breaking the metronome. The two classes spin independently of one another, which makes for code that is easier to maintain.

class Program
{
    static void Main()
    {
        // setup the metronome and make sure the EventHandler delegate is ready
        Metronome metronome = new Metronome();

        // wires up the metronome_Tick method to the EventHandler delegate
        Listener listener = new Listener(metronome);
        ListenerB listenerB = new ListenerB(metronome);
        metronome.Go();
    }
}

public class Metronome
{
    // a delegate
    // so every time Tick is called, the runtime calls another method
    // in this case Listener.metronome_Tick and ListenerB.metronome_Tick
    public event EventHandler Tick;

    // virtual so can override default behaviour in inherited classes easily
    protected virtual void OnTick(EventArgs e)
    {
        // null guard so if there are no listeners attached it wont throw an exception
        if (Tick != null)
            Tick(this, e);
    }

    public void Go()
    {
        while (true)
        {
            Thread.Sleep(2000);
            // because using EventHandler delegate, need to include the sending object and eventargs 
            // although we are not using them
            OnTick(EventArgs.Empty);
        }
    }
}


public class Listener
{
    public Listener(Metronome metronome)
    {
        metronome.Tick += new EventHandler(metronome_Tick);
    }

    private void metronome_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("Heard it");
    }
}

public class ListenerB
{
    public ListenerB(Metronome metronome)
    {
        metronome.Tick += new EventHandler(metronome_Tick);
    }

    private void metronome_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("ListenerB: Heard it");
    }
}   

Full article I'm writing on my site: http://www.programgood.net/

nb some of this text is from http://www.akadia.com/services/dotnet_delegates_and_events.html

Cheers.

7
ответ дан 4 December 2019 в 08:16
поделиться

На самом базовом концептуальном уровне события - это то, что позволяет компьютеру реагировать на то, что вы делаете, а не на вас. реагировать на то, что делает компьютер. Когда вы сидите перед компьютером с несколькими запущенными приложениями (включая операционную систему) и несколькими интерактивными объектами, доступными в каждом контексте, из которых вы можете выбирать, события - это то, что происходит, когда вы выбираете одну, и все вовлеченные части могут быть Правильно уведомлен.

Даже перемещение вашей мыши запускает поток событий (например, для перемещения курсора).

1
ответ дан 4 December 2019 в 08:16
поделиться

Вы можете реализовать шаблон наблюдателя в C # с помощью событий и делегатов.

Вот ссылка на статью, которая описывает такое: http://blogs.msdn.com/bashmohandes/archive/2007/03/10/observer-pattern-in-c-events-delegates.aspx

enter image description here

7
ответ дан 4 December 2019 в 08:16
поделиться

Вы всегда можете создать свой собственный способ отправки / получения событий, подписываясь / отписываясь от источников событий. Но язык дает вам простой / стандартный способ сделать это, так что это хорошая причина использовать языковые «события» вместо вашей собственной техники событий.

Также, использование языка «события» позволяет вам делать разные интересные вещи, используя рефлексию, потому что она стандартизирована.

Относительно того, почему вообще используется техника событий. Существуют всевозможные примеры из реальной жизни, где это довольно полезно и проще для использования событий. По своей полезности события почти аналогичны сообщениям Windows.

1
ответ дан 4 December 2019 в 08:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: