[英]How to extend C# built-in types, like String?
大家好...我需要Trim
一個String
。 但是我想刪除 String 本身中所有重復的空格,而不僅僅是在它的末尾或開頭。 我可以用這樣的方法來做到這一點:
public static string ConvertWhitespacesToSingleSpaces(string value)
{
value = Regex.Replace(value, @"\s+", " ");
}
我從這里得到的。 但是我希望在String.Trim()
本身中調用這段代碼,所以我認為我需要擴展或重載或覆蓋Trim
方法......有沒有辦法做到這一點?
提前致謝。
因為你不能擴展string.Trim()
。 您可以按照此處所述制作一個擴展方法來修剪和減少空格。
namespace CustomExtensions
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static string TrimAndReduce(this string str)
{
return ConvertWhitespacesToSingleSpaces(str).Trim();
}
public static string ConvertWhitespacesToSingleSpaces(this string value)
{
return Regex.Replace(value, @"\s+", " ");
}
}
}
你可以像這樣使用它
using CustomExtensions;
string text = " I'm wearing the cheese. It isn't wearing me! ";
text = text.TrimAndReduce();
給你
text = "I'm wearing the cheese. It isn't wearing me!";
有可能嗎? 是的,但只能使用擴展方法
System.String
類是密封的,因此您不能使用覆蓋或繼承。
public static class MyStringExtensions
{
public static string ConvertWhitespacesToSingleSpaces(this string value)
{
return Regex.Replace(value, @"\s+", " ");
}
}
// usage:
string s = "test !";
s = s.ConvertWhitespacesToSingleSpaces();
你的問題有一個是和一個否。
是的,您可以使用擴展方法擴展現有類型。 擴展方法自然只能訪問該類型的公共接口。
public static string ConvertWhitespacesToSingleSpaces(this string value) {...}
// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()
不,您不能調用此方法Trim()
。 擴展方法不參與重載。 我認為編譯器甚至應該給你一條錯誤消息,詳細說明這一點。
擴展方法僅在包含定義方法的類型的命名空間正在使用時才可見。
public static class MyExtensions
{
public static string ConvertWhitespacesToSingleSpaces(this string value)
{
return Regex.Replace(value, @"\s+", " ");
}
}
除了使用擴展方法——這里可能是一個很好的候選者——還可以“包裝”一個對象(例如“對象組合”)。 只要包裝形式包含的信息不比被包裝的事物多,那么包裝的項目就可以通過隱式或顯式轉換干凈利落地傳遞而不會丟失信息:只是類型/接口的更改。
快樂編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.