[英]C# 3.5 partial class String IsNullOrWhiteSpace
我正在嘗試為String
class ( IsNullOrWhitespace
,如 .NET4 )創建額外的功能,但我在引用時遇到問題:
錯誤 1 'String' 是 'string' 和 'geolis_export.Classes.String' 之間的模糊引用
我不想創建擴展方法。 因為如果string x = null;
這將崩潰
用法:
private void tbCabineNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !e.Text.All(Char.IsNumber) || String.IsNullOrWhiteSpace(e.Text);
}
字符串部分:
public partial class String
{
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
}
不能為String
class 創建額外內容嗎? 我試圖將部分放在System
命名空間中,但這會產生其他錯誤。
將String
重命名為String2
也可以解決問題。 但這不是我想要的,因為那時沒有引用原始String
class。
不可能這樣,因為.NET框架中的string
class不偏。
相反,使用像這樣的真正的擴展方法:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
}
用法將是這樣的:
string s = "test";
if(s.IsNullOrWhiteSpace())
// s is null or whitespace
與所有擴展方法一樣,如果字符串為null
,則調用不會導致 null 引用異常:
string s = null;
if(s.IsNullOrWhiteSpace()) // no exception here
// s is null or whitespace
出現這種行為的原因是編譯器會將這段代碼翻譯成等效於以下 IL 代碼的 IL 代碼:
string s = null;
if(StringExtensions.IsNullOrWhiteSpace(s))
// s is null or whitespace
擴展方法必須定義為 static class 中的static 方法。 還要注意參數上的this
關鍵字。
public static class MyExtensions
{
public static bool IsNullorWhitespace(this string input)
{
// perform logic
}
}
您通過在static
上省略 static 所做的是在您的程序集中定義一個競爭的 class ,因此來自編譯器的模棱兩可的消息。
string
class 未聲明為部分字符串,您必須改為編寫擴展方法。
public static class MyExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
if (value == null) return false;
return string.IsNullOrEmpty(value.Trim());
}
}
這不是您創建擴展方法的方式。 class 不是部分的,它需要是 static class 並且可以命名為任何名稱(MyExtensionMethods)。 您還需要在擴展方法上用“this”標記您的參數。
試試這個
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
}
為了創建擴展方法,您需要使用以下語法。 (注意關鍵字this
的使用):
public static bool IsNullOrWhiteSpace(this string value)
修剪字符串會導致可避免的字符串分配(這會損害性能)。 最好依次檢查每個字符而不分配任何內容:
public static bool IsNullOrWhiteSpace(this string value)
{
#if NET35
if (value == null)
return true;
foreach (var c in value)
{
if (!char.IsWhiteSpace(c))
{
return false;
}
}
return true;
#else
return string.IsNullOrWhiteSpace(value);
#endif
}
#if NET35
代碼意味着回退實現僅在針對 .NET 3.5 時存在。 您可以根據需要調整該比較以滿足項目的目標框架。 否則,將使用默認的string.IsNullOrWhiteSpace
方法,並且此 util 方法可能會被內聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.