扩展方法不编译(类型'字符串'没有定义)

cva*_*dal 2 c# linq itemssource

我正在尝试使用下面的代码将字节转换为KB/MB/GB,但是,我似乎无法让它工作.配额的价值是60000000000.

    public static double BytesToKilobytes(this Int32 bytes)
    {
        return bytes / 1000d;
    }

    public static double BytesToMegabytes(this Int32 bytes)
    {
        return bytes / 1000d / 1000d;
    }

    public static double BytesToGigabytes(this Int32 bytes)
    {
        return bytes / 1000d / 1000d / 1000d;
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
            return;

        XDocument xDocument = XDocument.Parse(e.Result);

        listBox1.ItemsSource = from query in xDocument.Descendants("service")
                               select new Service
                               {
                                   type = query.Attribute("type").Value,
                                   id = query.Element("id").Value,
                                   plan = query.Element("username").Value,
                                   quota = query.Element("quota").Value.BytesToGigabytes,                                   };
    }
Run Code Online (Sandbox Code Playgroud)

上面代码产生的错误是:

"'string'不包含'BytesToGigabytes'的定义,并且没有扩展方法'BytesToGigabytes'接受类型'string'的第一个参数可以找到(你是否缺少using指令或汇编引用?)"

Guf*_*ffa 5

由于配额是一个字符串,您必须先将其解析为一个数字:

quota = Decimal.Parse(query.Element("quota").Value).BytesToGigabytes()
Run Code Online (Sandbox Code Playgroud)

由于数字太大而无法容纳32位整数,因此必须使用Decimal:

public static Decimal BytesToGigabytes(this Decimal bytes) {
  return bytes / 1000m / 1000m / 1000m;
}
Run Code Online (Sandbox Code Playgroud)

也可以使用Int64,但该方法会截断结果,例如返回3 GB而不是3.9 GB.