【C#】通过扩展对象的方式,对字符串等数据类型进行数据进一步处理

138 阅读2分钟

我正在参加「掘金·启航计划」

在本篇文章中,我们讲一起了解下对象扩展的使用
在实际项目开发中,对象扩展使用的场景还是挺多的,比如:需要对时间值进行再处理,或者字符串中的斜杠(/)转为反斜杠(\)

  • 主要知识点列表 | 编号 | 语言或插件 | 知识点 | 说明 | | --- | --- | --- | --- | | 1 | C# | this | 通过this+数据类型+变量名 | | 2 | C# | ToUpper() | 将字符串转为大写 | | 3 | C# | Substring(下标, 长度) | 截取字符串 |

【扩展对象】

1)必须是在非泛型静态类下定义扩展方法

image.png

2)正确的扩展写法,在class关键词前添加static关键词

3)静态类,成员必须是静态,所以方法也必须设置成静态 image.png

  • 扩展的基础代码格式
public static class TestExtend
{
    public static string FirstBig(this string from_text, string string_text)
    {
        string new_text = string.Empty;

        return new_text;
    }
}

【内置函数实现首字母大写】

通过扩展方法,实现首字母大写的功能,实现的方式有很多

1)首先肯定需要判断字符串是否有值,null和""空值均不做处理

2)如果只存在一个长度字符串,那么直接转为大写返回,

3)如果大于等于两个长度字符串,那么通过截取方法,获取第一字符串以及之后的所有字符串

  • 代码
public static class TestExtend
{
    public static string FirstBig(this string from_text, string string_text)
    {
        string new_text = string.Empty;

        if (string.IsNullOrEmpty(from_text))
        {
            return new_text;
        }
        else if (from_text.Length == 1)
        {
            new_text = from_text.ToUpper();
            return new_text;
        }

        string first_text = from_text.Substring(0, 1);
        string other_text = from_text.Substring(1, from_text.Length - 2);

        new_text = first_text.ToUpper() + other_text;

        return new_text;
    }
}

image.png

4)方法进一步修改完善,通过遍历的方式,把所有单词的首个字母转为大写

  • 代码
public static string FirstBig(this string from_text)
{
    string new_text = string.Empty;

    if (string.IsNullOrEmpty(from_text))
    {
        return new_text;
    }
    else if (from_text.Length == 1)
    {
        new_text = from_text.ToUpper();
        return new_text;
    }

    bool first_flag = false;
    foreach (char item in from_text)
    {
        bool flag = Regex.Matches(item.ToString(), "[a-zA-Z]").Count > 0;
        if (flag && !first_flag)
        {
            first_flag = true;
            new_text += item.ToString().ToUpper();
        }
        else if (flag)
        {
            new_text += item.ToString();
        }
        else
        {
            first_flag = false;
            new_text += item.ToString();
        }
    }

    return new_text;
}
}
  • 效果 image.png

【将字符串中的反斜杠转为斜杠】

1)在windows操作系统下,文件和文件夹的路径是反斜杠方式

image.png

2)如果保存在数据库中,那么在web项目中使用,前端虽然也能识别,但是看着别扭。在一些特殊情况有时会报错,所以需要统一转为斜杠方式

  • 代码
public static class TestExtend
{
    public static string NewPath(this string from_text)
    {
        return from_text.Replace("\\","/");
    }
}

image.png