类型参数约束 - 没有泛型(或最近的提议!) [英] Type Parameter Constraints - no generics (or nearest offer!)
问题描述
我想我想做的是不可能的,但我想我会问。我想在不同的指标测量之间实现某种自定义转换 - 例如将英寸转换为米和其他单位。
I am thinking what I want to do is impossible but thought I would ask anyway. I am thinking of implementing some kind of custom conversion between different metric measurements - such as converting inches to metres and other units.
我认为基本类称为Unit如下。注意:我没有在任何字段中保存单位数,例如2米,5英寸等:
I am thinking base class called Unit as follows. NOTE: I have not put in any fields to hold the number of units eg 2 metres, 5 inches and so on:
public abstract class Unit {
protected string _name;
public Unit(string name)
{
_name = name;
}
}
然后是Meter和Inch的Unit子类: p>
Then subclasses of Unit for Metre and Inch:
public class Metre : Unit {
public Metre() : base("Metre")
{
}
}
public class Inch : Unit {
public Metre() : base("Inch")
{
}
}
我想有一个类,可以处理这些单位之间的转换。例如:
I would like to have a class that could handle conversion of these units between one another. Something like:
public static class UnitConvertor
{
public Unit Convert(Unit from, Type to) : where Type extends/inherits from Unit
{
// do the conversion
return the instance of Type to;
}
}
有任何想法吗?
推荐答案
如果提前提前知道单位,您可以使用隐式转换运算子:
If the units are all known ahead of time you could use an implicit conversion operator:
public class Metre : Unit
{
public Metre() : base("Metre")
{
}
public static implicit operator Inch(Metre m)
{
return new Inch(39.37 * m.Value);
}
}
这篇关于类型参数约束 - 没有泛型(或最近的提议!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!