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