// 定义一个静态类来包含扩展方法
public static class StringExtensions
{
// 定义一个扩展方法,为 string 类型添加一个新的方法 IsNullOrEmpty
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
// 定义另一个扩展方法,为 string 类型添加一个新的方法 ToTitleCase
public static string ToTitleCase(this string str)
{
if (string.IsNullOrEmpty(str))
return str;
System.Globalization.TextInfo textInfo = new System.Globalization.CultureInfo("en-US", false).TextInfo;
return textInfo.ToTitleCase(str);
}
}
// 使用扩展方法的示例代码
class Program
{
static void Main()
{
string testString = "hello world";
// 调用扩展方法 IsNullOrEmpty
bool isNull = testString.IsNullOrEmpty();
Console.WriteLine($"Is the string null or empty? {isNull}");
// 调用扩展方法 ToTitleCase
string titleCaseString = testString.ToTitleCase();
Console.WriteLine($"Title case: {titleCaseString}");
}
}
StringExtensions 是一个静态类。this 关键字的第一个参数的方法。例如,IsNullOrEmpty 和 ToTitleCase 方法都是扩展方法。testString.IsNullOrEmpty() 和 testString.ToTitleCase()。string)添加新的功能,而无需修改这些类型的源代码。希望这个示例能帮助你理解 C# 中的扩展方法!
上一篇:c# math
下一篇:c# 列表
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站