使用自定义类扩展类型

Tho*_*ian 2 c#

我想知道一些事情.而不是写入String.Format("{0:X}", num);将数字转换为十六进制.有没有办法我可以直接扩展字符串,以便我可以简单地写num.ToHex();

Zbi*_*iew 6

您可以创建扩展方法:

public static class IntExtensions
{
    public static string ToHex(this int source)
    {
        return string.Format("{0:X}", source);
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样执行:

string hexNum = 1234.ToHex();
Run Code Online (Sandbox Code Playgroud)