C#的this扩展

2018-10-23  本文已影响0人  好大一棵树6

C#中使用this给原有的类添加方法,调用起来很方便。

一、例子

给string更改颜色

public static class StringTool
{
    public static string GreenColor(this string str)
    {
        return "<color=#00FF17FF>" + str + "</color>";
    }
    public static string RedColor(this string str)
    {
        return "<color=#FF0010FF>" + str + "</color>";
    }
}

调用方式

string str = "hello world";
str = str.GreenColor();

这样在显示的时候str就带了绿色的标记,就成为了绿色。

二、条件

上一篇 下一篇

猜你喜欢

热点阅读