65.9K
CodeProject 正在变化。 阅读更多。
Home

创建基本扩展方法

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (8投票s)

2007年10月1日

CPOL

2分钟阅读

viewsIcon

37591

downloadIcon

377

使用 .toHTML() 扩展 System.Color

Screenshot - HTMLExt.gif

背景

许多开发者都曾遇到过类缺少他们想要/需要的功能的情况。有多少次你在开发项目时希望 Integer 类型能直接内置 .toHex() 函数?

一些开发者创建了包装类,这些类允许你向现有对象添加虚拟函数,比如使用名为 .toPiglatin() 的新虚拟方法来扩展 System.String

使用 .NET 3,你不再需要使用这些扩展方法,它已经内置在语言中。我将向你展示如何创建一个简单的扩展,它是 color 类型的一部分,名为 .toHTML()

构建扩展类

这不能再简单了。

using System;

namespace HTMLExt
{
    public static class MyExtensions
    {
        public static string toHex(this System.Byte thisNumber)
        {
            return String.Format("{0:x2}", thisNumber).ToUpper();
        }

        public static string toHTML(this System.Drawing.Color thisColor)
        {
            return String.Format("#{0}{1}{2}", thisColor.R.toHex(), 
			thisColor.G.toHex(), thisColor.B.toHex());
        }
    }
}

这是整个程序的核心,你可以在这里定义扩展现有对象的方法。首先,你需要命名你的命名空间,并将 MyExtensions 类设为 static

第一个是简单的 .toHex() 扩展,它将扩展 System.Byte,因此你可以使用如下语句:

string HexValue = Color.Red.R.toHex();

这将产生预期的结果 FF。

第二个扩展名为 .toHTML(),它扩展了 System.Drawing.Color
此扩展的功能是将所有 .toHex() 结果格式化为有效的 HTML 颜色并返回,因此你可以执行以下操作:

string HTMLColor = Color.Blue.toHTML(); 

这将产生预期的结果 #0000FF。

示例应用

示例应用程序的功能是获取你使用标准 colorDialog 选择的颜色,并返回其 HTML 值。这是完成所有操作的函数:

private void button1_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
        HtmlColor.Text = colorDialog1.Color.toHTML();
}

非常简单明了,它显示一个颜色对话框,然后将所选颜色转换为 HTML。好了,这篇简短的文章就到此为止,希望你玩得开心。我已经想到了一些用途了。

Extensions.zip

这些是我编写的其他一些扩展,用于启动我的核心扩展库

  • Byte.ToHex()

    将字节转换为其十六进制值。(也适用于 Int16、32、64 和 UInt16、32、64)

  • Color.ToHTML()

    将颜色转换为其 HTML 颜色字符串

  • Char.ToUpper()

    Char 转换为大写

  • Char.ToLower()

    char 转换为小写

  • String.isNumber()

    给定的 string 是数字吗?

  • String.isEmail()

    给定的 string 是电子邮件地址吗?

  • String.IsURL()

    给定的 string 是有效的 URL 吗(格式:http://devclarity.com

  • String.ContainsPunctuation()

    给定的 string 中是否有任何标点符号

  • String.ToTitle()

    string 转换为首字母大写(每个单词的首字母大写)

  • String.ToProper()

    string 转换为首字母大写(第一个字母大写)

  • String.ToPigLatin() [totally useless]

    string 转换为猪拉丁语

  • ICollection<string>.Join(", ")

    连接一个由逗号分隔的 string 数组或集合

  • ICollection<int>.Join(", ")

    连接一个由逗号分隔的整数数组或集合

© . All rights reserved.