简体   繁体   English

C# 3.5 部分 class 字符串 IsNullOrWhiteSpace

[英]C# 3.5 partial class String IsNullOrWhiteSpace

I'm trying to create extra functionality to the String class ( IsNullOrWhitespace as in .NET4 ) But I'm having an problem with referencing:我正在尝试为String class ( IsNullOrWhitespace ,如 .NET4 )创建额外的功能,但我在引用时遇到问题:

Error 1 'String' is an ambiguous reference between 'string' and 'geolis_export.Classes.String'错误 1 'String' 是 'string' 和 'geolis_export.Classes.String' 之间的模糊引用

I don't want to create an extension method.我不想创建扩展方法。 Because this will crash if string x = null;因为如果string x = null;这将崩溃

Usage:用法:

private void tbCabineNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !e.Text.All(Char.IsNumber) || String.IsNullOrWhiteSpace(e.Text);
}

String partial:字符串部分:

public partial class String
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

Is it not possible to create extras for the String class?不能为String class 创建额外内容吗? I have tried to put the partial in the System namespace, but this gives other errors.我试图将部分放在System命名空间中,但这会产生其他错误。

Renaming String to String2 fixes the problem also.String重命名为String2也可以解决问题。 But this is not what I want, because then there is no reference with the original String class.但这不是我想要的,因为那时没有引用原始String class。

It is not possible like this, because the string class in the .NET framework is not partial.不可能这样,因为.NET框架中的string class不偏。
Instead, use a real extension method like this:相反,使用像这样的真正的扩展方法:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

The usage would then be like this:用法将是这样的:

string s = "test";
if(s.IsNullOrWhiteSpace())
    // s is null or whitespace

As with all extension methods, the call will not result in a null reference exception if the string is null :与所有扩展方法一样,如果字符串为null ,则调用不会导致 null 引用异常:

string s = null;
if(s.IsNullOrWhiteSpace()) // no exception here
    // s is null or whitespace

The reason for this behavior is that the compiler will translate this code into IL code that is equivalent to the IL code of the following:出现这种行为的原因是编译器会将这段代码翻译成等效于以下 IL 代码的 IL 代码:

string s = null;
if(StringExtensions.IsNullOrWhiteSpace(s))
    // s is null or whitespace

An extension method has to be defined as a static method inside a static class.扩展方法必须定义为 static class 中的static 方法 Also notice the this keyword on the parameter.还要注意参数上的this关键字。

public static class MyExtensions
{
    public static bool IsNullorWhitespace(this string input)
    {
         // perform logic
    }
}

What you have done by omitting the static on the class is define a competing class within your assembly, hence the ambiguous message from the compiler.您通过在static上省略 static 所做的是在您的程序集中定义一个竞争的 class ,因此来自编译器的模棱两可的消息。

The string class is not declared as partial, you will have to write an extension method instead. string class 未声明为部分字符串,您必须改为编写扩展方法。

public static class MyExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return false;
        return string.IsNullOrEmpty(value.Trim());
    }
}

That isn't how you create an extension method.这不是您创建扩展方法的方式。 The class isn't a partial, it needs to be a static class and it can be named anything (MyExtensionMethods). class 不是部分的,它需要是 static class 并且可以命名为任何名称(MyExtensionMethods)。 You also need to mark your parameter with "this" on an extension method.您还需要在扩展方法上用“this”标记您的参数。

Try this instead试试这个

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

In order to create an extension method, you need to use the following syntax.为了创建扩展方法,您需要使用以下语法。 (Note the use of the keyword this ): (注意关键字this的使用):

public static bool IsNullOrWhiteSpace(this string value)

Trimming the string results in an avoidable string allocation (which can hurt performance).修剪字符串会导致可避免的字符串分配(这会损害性能)。 Better to check each character in turn and not allocate anything:最好依次检查每个字符而不分配任何内容:

        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
        }

The #if NET35 code means that the fallback implementation exists only when targeting .NET 3.5. #if NET35代码意味着回退实现仅在针对 .NET 3.5 时存在。 You can adjust that comparison to meet your project's target frameworks as needed.您可以根据需要调整该比较以满足项目的目标框架。 Otherwise, the default string.IsNullOrWhiteSpace method is used, and this util method would likely be inlined.否则,将使用默认的string.IsNullOrWhiteSpace方法,并且此 util 方法可能会被内联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM