【发布时间】:2016-06-22 09:03:29
【问题描述】:
在 form1 中我添加了两个类
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private const Decimal OneKiloByte = 1024M;
private const Decimal OneMegaByte = OneKiloByte * 1024M;
private const Decimal OneGigaByte = OneMegaByte * 1024M;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
if (arg is string)
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneGigaByte)
{
size /= OneGigaByte;
suffix = "GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = "MB";
}
else if (size > OneKiloByte)
{
size /= OneKiloByte;
suffix = "kB";
}
else
{
suffix = " B";
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
IFormattable formattableArg = arg as IFormattable;
if (formattableArg != null)
{
return formattableArg.ToString(format, formatProvider);
}
return arg.ToString();
}
}
public static class ExtensionMethods
{
public static string ToFileSize(this long l)
{
return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
}
}
然后我像这样使用它:
FileInfo fi = new FileInfo(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
label17.Text = ExtensionMethods.ToFileSize(fi.Length);
但是在 ToFilesize 上的 ExtensionMethods 类上出现错误:
错误1 扩展方法必须定义在顶级静态类中; ExtensionMethods 是一个嵌套类
【问题讨论】:
-
您在此处发布的代码与错误消息不匹配。您能向我们展示代码所在的整个 CS 文件吗?
-
@מני מנחם 是否有“以上”类
FileSizeFormatProvider? -
@nozzleman 是的,但它不是直接在 FileSizeFormatProvider 类之上,之前有一些方法。
-
您需要正确定义该扩展方法(在顶级静态类中)。或者删除“this”关键字,以您当前的方式将其用作常规帮助方法。