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");
}
/// <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");
}
相关文章推荐
- VS 2008 + .NET 3.5 - C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Extension Methods(扩展方法)
- C#2008语言特征3----扩展方法
- C#2008新特性--(扩展方法)Extension Method
- 步步为营VS 2008 + .NET 3.5(3) - C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Extension Methods(扩展方法)
- 3、步步为营VS 2008 + .NET 3.5(3) - C# 3.0新特性之Automatic Properties(自动属性)、Object Initializers(对象初始化器)、Collection Initializers(集合初始化器)和Extension Methods(扩展方法)
- C#用扩展方法进行自动生成添加删除对象转换的功能
- 【原创】开源Math.NET基础数学类库使用(12)C#随机数扩展方法
- C#扩展方法知多少
- c# 扩展方法奇思妙用基础篇 六:WhereIf 扩展
- C#:USB设备枚举(七)WPF扩展方法
- C#扫盲之:带你掌握C#的扩展方法、以及探讨扩展方法的本质、注意事项
- c# 扩展方法奇思妙用 ASP.NET MVC 篇:巧用扩展方法优先级,美化所有页面 TextBoxFor 文本框
- C# 扩展方法
- C#_扩展方法
- 扩展方法(C#)
- c#中的扩展方法
- c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
- C#原始类型扩展方法—this参数修饰符
- C#扩展方法
- [C# 基础知识系列]专题十五:全面解析扩展方法