Eri*_*tas 13 c# events eventargs
我理解使用标准MS事件处理程序委托签名的好处,因为它允许您轻松扩展通过事件传递的信息,而不会破坏任何基于旧委托签名的旧关系.
我想知道在实践中人们经常遵循这条规则吗?说我有一个像这样的简单事件
public event NameChangedHandler NameChanged;
public delegate void NameChangedHandler(Object sender, string oldName, string newName);
Run Code Online (Sandbox Code Playgroud)
这是一个简单的事件,我几乎肯定我从NameChanged事件中需要知道的唯一参数是名称已更改的对象,旧名称和新名称.那么创建一个单独的NameChangedEventArgs类是否值得,或者像这样的简单事件是否可以直接通过委托参数返回参数?
Sam*_*ell 10
EventHandler<T>
对事件使用通用委托,并创建派生类型EventArgs
以保存事件数据.换句话说,永远.当你遇到它时,你总是知道它是如何工作的,因为它从来没有做过.
编辑:
代码分析CA1003:使用通用事件处理程序实例
代码分析CA1009:正确声明事件处理程序
如果你是唯一一个必须处理它的人,你可以采取任何错误的方式.但是,学习标准并坚持下去并不是一个坏主意,以便在与他人合作时保持良好的习惯.
所以我会帮你做个交易.如果你保证以正确的方式做到这一点,我会给你一个代码片段,这样可以减轻痛苦.只需将其放在.snippet文件中,并将该文件放入:
我的Documents\Visual Studio 2008\Code Snippets\Visual C#\ My Code Snippets\
(或Visual Studio 2005,如果适用)
这是片段; 通过输入ev2Generic并点击Tab键在VS中使用它:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Generic event with two types/arguments.</Title>
<Shortcut>ev2Generic</Shortcut>
<Description>Code snippet for event handler and On method</Description>
<Author>Kyralessa</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type1</ID>
<ToolTip>Type of the first property in the EventArgs subclass.</ToolTip>
<Default>propertyType1</Default>
</Literal>
<Literal>
<ID>arg1Name</ID>
<ToolTip>Name of the first argument in the EventArgs subclass constructor.</ToolTip>
<Default>property1Name</Default>
</Literal>
<Literal>
<ID>property1Name</ID>
<ToolTip>Name of the first property in the EventArgs subclass.</ToolTip>
<Default>Property1Name</Default>
</Literal>
<Literal>
<ID>type2</ID>
<ToolTip>Type of the second property in the EventArgs subclass.</ToolTip>
<Default>propertyType2</Default>
</Literal>
<Literal>
<ID>arg2Name</ID>
<ToolTip>Name of the second argument in the EventArgs subclass constructor.</ToolTip>
<Default>property2Name</Default>
</Literal>
<Literal>
<ID>property2Name</ID>
<ToolTip>Name of the second property in the EventArgs subclass.</ToolTip>
<Default>Property2Name</Default>
</Literal>
<Literal>
<ID>eventName</ID>
<ToolTip>Name of the event</ToolTip>
<Default>NameOfEvent</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[public class $eventName$EventArgs : System.EventArgs
{
public $eventName$EventArgs($type1$ $arg1Name$, $type2$ $arg2Name$)
{
this.$property1Name$ = $arg1Name$;
this.$property2Name$ = $arg2Name$;
}
public $type1$ $property1Name$ { get; private set; }
public $type2$ $property2Name$ { get; private set; }
}
public event EventHandler<$eventName$EventArgs> $eventName$;
protected virtual void On$eventName$($eventName$EventArgs e)
{
var handler = $eventName$;
if (handler != null)
handler(this, e);
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4817 次 |
最近记录: |