转换的扩展方法

时间:2016-07-26 05:37:28

标签: c# extension-methods

让我们假设我有一个如下课程:

public class PhysicalMemory 
{ 
    public string Localtion { get; internal set; } 
    public ulong Capacity { get; internal set; } 
    public string Manufacturer { get; internal set; } 
    public string Part_Number { get; internal set; } 
    public string Serial_Number { get; internal set; } 
    public uint Speed { get; internal set; }
}

我需要一种扩展方法,将我的容量从字节转换为KBytes,MBytes和.....如果用户想要,例如:

PhysicalMemory phM = New PhysicalMemory();
ulong capacity_in_bytes = phM.Capacity;

ulong capacity_in_KB = phM.Capacity.ToKBytes();
ulong capacity_in_MB = phM.Capacity.ToMBytes();

3 个答案:

答案 0 :(得分:3)

为此目的使用扩展方法没有意义。即使可以在这里编写其他人所示的扩展方法,你也真的需要远离这样做。如果你写一个,它只是一个将X ulong转换为Y ulong的方法。

您可以在这里做的最好的事情就是添加相应的属性或方法来转换容量。我宁愿只拥有只读属性。这比使用单独的扩展方法更简单。

public class PhysicalMemory 
{ 
    public ulong Capacity { get; internal set; } 
    public ulong CapacityMB { get { return Capacity / (1024 * 1024); } } 
    public ulong CapacityKB { get { return Capacity / 1024; } } 
}

答案 1 :(得分:2)

public static class ULongExtensions
{
    public static ulong ToKBytes(this ulong memory)
    {
        return memory / 1024;
    }

    public static ulong ToMByptes(this ulong memory)
    {
        return memory.ToKBytes() / 1024;
    }
}     

答案 2 :(得分:0)

如果您已创建类PhysicalMemory,则无法创建扩展方法。这些用于扩展您无法修改的类(出于某种原因)。

ulong中存储MB值也没有意义。这样您就无法区分2.1 MB2.2 MB。我认为您不希望出现这种行为,最好选择decimaldouble

但是,你可以这样做:

public static class MyExtensions
{
    public static decimal ToKBytes(this ulong value)
    {
        return value / (decimal)1024;
    }

    public static decimal ToMBytes(this ulong value)
    {
        return value / ((decimal)1024 * 1024);
    }
}

我强烈建议不要使用这些方法扩展ulong类型。这对我没有任何意义。创建一些转换模块或将方法添加到您的类(可能作为属性)