关于链式调用

本文介绍了C#中的链式调用和扩展方法,通过示例展示了如何为int和string类型添加扩展方法,以及如何在Entity Framework中使用链式编程。此外,还探讨了如何处理void方法的链式调用问题,并提供了使用泛型扩展方法的解决方案。
摘要由CSDN通过智能技术生成
    • 举个例子

链式调用,方法链(method chaining)是面向对象的编程语言中的一种常见语法,可以让开发者在只引用对象一次的情况下,对同一个对象进行多次方法调用。虽然链式调用不包含在23种设计模式,但它是一种常用的代码设计方式。

扩展方法,使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种静态方法,但可以像扩展类型上的实例方法一样进行调用。

在编写代码的时候,使用链式调用可以使代码的行为更加清晰,而扩展方法则可以在不修改原有类型(包括int、string等内置类型)的基础上为类型添加行为。

举个例子,为C#的int、string类型添加方法:

using System;

using System.Text;

namespace ExampleProject

{

class Program

{

static void Main(string[] arg)

{

int num = 1.Plus(40)

.Plus(9)

.Subtract(2)

.Multi(10)

.Divide(2);

string str = "Hello World!".Add(" This is C#.")

.Remove(" World");

Console.WriteLine(num);

Console.WriteLine(str);

}

}

///<summary>

///int类型的扩展方法

///</summary>

public static class class1

{

public static int Plus(this int num1,int num2)

{

return num1+num2;

}

public static int Subtract(this int num1,int num2)

{

return num1-num2;

}

public static int Multi(this int num1,int num2)

{

return num1*num2;

}

public static int Divide(this int num1,int num2)

{

return num1/num2;

}

}

///<summary>

///string类型的扩展方法

///</summary>

public static class class2

{

public static string Add(this string str1,string str2)

{

return str1+str2;

}

public static string Remove(this string str1,string str2)

{

string[] strs = str1.Split(new string[]{str2},StringSplitOptions.RemoveEmptyEntries);

str1 = "";

foreach (var item in strs)

{

str1+=item;

}

return str1;

}

}

}

//输出:

//240

//Hello! This is C#.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值