Java开发人员的C#:扩展方法

After spending several years crafting Java code, I recently decided to dive back into C# and share what I learn in the process. In this blog post, I will talk about extensions methods. This concept, which exists in some JVM languages (like Kotlin) but not in Java, let the developer add methods to a class without touching its code (hence the name extension methods).

假设您要创建一个方法,将字符串的首字母大写,然后返回新字符串。 您不能修改(甚至继承)串Java中的类添加此方法。 由于您不一定要创建自己的自定义样式串您的代码库的类,您可能会创建一个静态函数,该函数需要一个串作为参数并返回另一个串:

class StringExtensions {
  static String capitalize(String word) {
      return Character.toUpperCase(word.charAt(0)) + word.substring(1);
  }
}

现在,您可以像这样简单地调用此函数:

String word = "hello";
String capitalizedWord = StringExtensions.capitalize(word);

当然,在C#中也可以创建静态方法。 但是,C#具有一项功能,该功能允许向类中添加新方法而不必修改其代码。 此功能称为扩展方法。 为了创建扩展方法,您必须创建一个顶级静态类并实现一个静态方法。 此方法的第一个参数指定该方法所操作的类型,并应具有这个修饰符:

static class StringExtensions
{
  static string Capitalize(this String word)
  {
      // Note that this cannot access any private data in the String class. 
      return char.ToUpper(word[0]) + word.Substring(1);
  }
}

为了使用它,包含类的名称空间必须用使用指示。 之后,可以像调用该实例方法一样调用该方法:

string word = "hello";
string capitalizedWord = word.Capitalize();

扩展方法非常强大。 除了代码看起来“干净”外,还可以通过简单地导入名称空间将新行为无缝地插入到现有类型中。 扩展代码可以位于单独的特定模块中,仅在需要时才可以导入。

from: https://dev.to//rnowif/c-for-the-java-developer-extension-methods-n69

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值