您的位置:首页 > 编程语言 > C#

让编写C#属性更加规范、容易

2010-11-03 11:22 337 查看
通常,在写C#类的属性时,会这样写:

public int Count { get; set; }

大多数软件公司都会要求添加注释,并对属性进行必要的扩展:

private int count;

/// <summary>
/// 玩具的数量
/// </summary>
public int Count
{
get
{
return count;
}
set
{
count = value;
}
}

我还有个习惯,是对属性更改前后提供事件通知,并且将跟属性相关的字段、属性、事件用#region包起来:

#region public int Count; // 玩具的数量

/// <summary>
/// 玩具的数量
/// </summary>
int count;

/// <summary>
/// 玩具的数量
/// </summary>
public int Count
{
get
{
return count;
}
set
{
if (count != value)
{
if (CountChanging != null)
{
CountChanging(count, value);
}
count = value;
if (CountChanged != null)
{
CountChanged(count);
}
}
}
}

/// <summary>
/// Count属性变更前
/// </summary>
public event Action<int, int> CountChanging;

/// <summary>
/// Count属性变更后
/// </summary>
public event Action<int> CountChanged;

#endregion

把#region收起来到效果,非常直观、简洁:





为此,我将VS.NET提供的propfull.snippet修改了下,保存为prope.snippet,分享给大家。只需要把下面的Code Snippet代码保存到C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC#/Snippets/2052/Visual C#下。在类里面敲入prope,然后按两次Tab键,即出来此代码段。试试吧!

prope.snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>prope</Title>
<Shortcut>prope</Shortcut>
<Description>属性和支持字段的代码段,能够发出属性更改事件。</Description>
<Author>http://blog.csdn.net/baiguli</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>属性类型</ToolTip>
<Default>int</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>属性名</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>支持此属性的变量</ToolTip>
<Default>myVar</Default>
</Literal>
<Literal>
<ID>description</ID>
<ToolTip>对此属性的描述</ToolTip>
<Default>说明</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[#region public $type$ $property$; // $description$

/// <summary>
/// $description$
/// </summary>
$type$ $field$;

/// <summary>
/// $description$
/// </summary>
public $type$ $property$
{
get
{
return $field$;
}
set
{
if ($field$ != value)
{
if ($property$Changing != null)
{
$property$Changing($field$, value);
}
$field$ = value;
if ($property$Changed != null)
{
$property$Changed($field$);
}
}
}
}

/// <summary>
/// $property$属性变更前
/// </summary>
public event Action<$type$, $type$> $property$Changing;

/// <summary>
/// $property$属性变更后
/// </summary>
public event Action<$type$> $property$Changed;

#endregion$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

一般的软件公司都有代码规范,但是执行起来往往不尽如人意。我想其中的原因大概可以归咎为“想说爱你不容易!”吧?如果公司写好许多符合代码规范的代码段,让程序员使用,各人写出来的代码就比较一致啦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: