Sti*_*nus 13 .net c# string .net-3.5
我正在尝试为类创建额外的功能String(IsNullOrWhitespace如在.NET4中)但是我在引用方面遇到了问题:
错误1'字符串'是'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);
}
Run Code Online (Sandbox Code Playgroud)
字符串部分:
public partial class String
{
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
}
Run Code Online (Sandbox Code Playgroud)
是不是可以为String班级创建额外的东西?我试图将部分放在System命名空间中,但这会产生其他错误.
重命名String以String2解决问题.但这不是我想要的,因为那时原始String类没有参考.
Dan*_*rth 45
这是不可能的,因为string.NET框架中的类不是部分的.
相反,使用这样的真正的扩展方法:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
if (value == null) return true;
return string.IsNullOrEmpty(value.Trim());
}
}
Run Code Online (Sandbox Code Playgroud)
用法如下:
string s = "test";
if(s.IsNullOrWhiteSpace())
// s is null or whitespace
Run Code Online (Sandbox Code Playgroud)
与所有扩展方法一样,如果字符串为null:则调用不会导致空引用异常:
string s = null;
if(s.IsNullOrWhiteSpace()) // no exception here
// s is null or whitespace
Run Code Online (Sandbox Code Playgroud)
此行为的原因是编译器将此代码转换为IL代码,该代码等效于以下IL代码:
string s = null;
if(StringExtensions.IsNullOrWhiteSpace(s))
// s is null or whitespace
Run Code Online (Sandbox Code Playgroud)
扩展方法必须被定义为一个静态方法一个内部静态类.还要注意this参数上的关键字.
public static class MyExtensions
{
public static bool IsNullorWhitespace(this string input)
{
// perform logic
}
}
Run Code Online (Sandbox Code Playgroud)
通过省略static类来完成的工作是在程序集中定义一个竞争类,因此来自编译器的模糊消息.
| 归档时间: |
|
| 查看次数: |
11478 次 |
| 最近记录: |