gpt4 book ai didi

c# - 事件 - 命名约定和风格

转载 作者:IT王子 更新时间:2023-10-29 03:46:42 25 4
gpt4 key购买 nike

我正在学习 C# 中的事件/委托(delegate)。我可以问一下您对我选择的命名/编码风格的看法吗(摘自 Head First C# 一书)?

我明天要教一个 friend 这方面的知识,并试图想出最优雅的方式来解释这些概念。 (认为​​理解一门学科的最好方法是尝试教授它!)

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);
metronome.OnTick();
}
}

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

public void OnTick()
{
while (true)
{
Thread.Sleep(2000);
// because using EventHandler delegate, need to include the sending object and eventargs
// although we are not using them
Tick(this, 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");
}
}

注意代码重构自 http://www.codeproject.com/KB/cs/simplesteventexample.aspx

最佳答案

Microsoft 实际上已经编写了大量的命名指南并将其放入 MSDN 库中。您可以在此处找到这些文章:Naming Guidelines

除了一般的大写指南外,以下是页面 Names of Type Members 上“事件”的内容:

✔️ DO name events with a verb or a verb phrase.

Examples include Clicked, Painting, DroppedDown, and so on.

✔️ DO give events names with a concept of before and after, using the present and past tenses.

For example, a close event that is raised before a window is closed would be called Closing, and one that is raised after the window is closed would be called Closed.

❌ DO NOT use "Before" or "After" prefixes or postfixes to indicate pre- and post-events. Use present and past tenses as just described.

✔️ DO name event handlers (delegates used as types of events) with the "EventHandler" suffix, as shown in the following example:

public delegate void ClickedEventHandler(object sender, ClickedEventArgs e);

✔️ DO use two parameters named sender and e in event handlers.

The sender parameter represents the object that raised the event. The sender parameter is typically of type object, even if it is possible to employ a more specific type.

✔️ DO name event argument classes with the "EventArgs" suffix.

关于c# - 事件 - 命名约定和风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/724085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com