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

C#2008扩展方法

2010-12-11 16:09 183 查看
扩展方法被定义为静态类中的静态方法,扩展方法的第一个参数必须是this关键字,后面跟着目标对象的类型,该类型规定了扩展方法可以在哪里应用,在该类型的对象上调用扩展方法,就像调用一个正常的方法一样。

/// <summary>
/// 说明:扩展方法被定义为静态类中的静态方法,扩展方法的第一个参数必须是
/// this关键字,后面跟着目标对象的类型,该类型规定了扩展方法可以在哪里应用
/// 扩展方法定义后,就像调用一个正常的方法一样。
/// </summary>
public static class IntegerExtensions
{
public static bool IsOdd(this int number)
{
return (number % 2) == 0 ? false : true;
}
public static bool IsEven(this int number)
{
return (number % 2) == 0 ? true : false;
}
}

方法调用

bool result = IntegerExtensions.IsOdd(6);
if (result)
{
Console.WriteLine("Odd");
}
else
{
Console.WriteLine("Even");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐