【问题标题】:where exactly implicit conversion method be put确切的隐式转换方法放在哪里
【发布时间】:2012-05-22 04:56:46
【问题描述】:
public class Faranheit 
{
    public float Digree { get; set; }

    public Faranheit(float f) 
    {
        Digree = f;
    }

    public static implicit operator Celcius(Faranheit f)
    {
        return new Celcius((5.0f / 9.0f) * (f.Digree - 32));
    }

    public static implicit operator Faranheit(Celcius c)
    {
        return new Faranheit((9.0f / 5.0f) * c.Digree + 32);
    }
}

public class Celcius
{
    public float Digree{get;set;}

    public Celcius(float c)
    {
        Digree = c;
    }

}

我只是很困惑,究竟该把转换方法放在哪里..

即使我将一种方法放在一个类中而将另一种方法放在另一个类中,或者我交换它们,或者即使我将它们都放在两个类中的任何一个中,它也能正常工作..

但是如果我把它放在这两个类之外它就不起作用(编译错误)..

请有人对此有所了解..

编辑:

如果它允许转换方法在任何一个类中,为什么它不允许转换方法在单独的类中??

【问题讨论】:

  • 你遇到了什么编译错误?
  • 小问题:它是“华氏度”。还有“学位”。
  • @AdamV:这不是我要说的......我不认为这是我的问题的原因......;)
  • @dotNETbeginner:这就是为什么我将其写为评论而不是答案的原因。 :)

标签: c# type-conversion implicit-conversion user-defined-types


【解决方案1】:

我会将它们放在每个班级中。因此,您可以执行以下操作:

Celsius c = new Celsius(Value);
Fahrenheit f = c.toFahrenheit();
Celsius newC = f.toCelsius();

编辑:或者如果你想走 Helper 类路线,你可以这样做:

public static class ConvertTemps
{
    public static Celsius toCelsius(Fahrenheit F)
    {
        return new Celsius(5/8* F - 32);
    }
    public static Fahrenheit toFahrenheit(Celsius C)
    {
        return new Fahrenheit(8/5*C + 32);
    }
}

然后您可以执行以下操作:

Celsius c = new Celsius(value);
Fahrenheit f = ConvertTemps.toFahrenheit(c);

但我会走第一条路线。

【讨论】:

  • 啊,我忽略了这一点。好点子。猜猜这是一个非常重要的。好吧,鉴于此,您肯定希望每个班级都有一个。
【解决方案2】:

重要的是隐式转换存在于两个类之一中。我倾向于将两种转换都放在不太常用的类中。

在这种情况下,类看起来是相等的,所以我会将转换到放在每个类中,即从 F 到 C 的转换将在摄氏度类中进行,反之亦然。

真的,这主要是关于个人喜好。

在这种特定情况下,我会编写一个温度类,让您获得 C、F、K、R 等单位的温度。但这与实际问题并不完全相关。

【讨论】:

  • 我的问题实际上是,如果它允许转换方法在任何一个类中,为什么不允许转换方法在单独的类中??
猜你喜欢
  • 2015-11-20
  • 2014-08-20
  • 2014-08-11
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多