类型参数约束 - 没有泛型(或最近的报价!)

And*_*dez 2 c# parameters constraints

我在想我想做什么是不可能的,但我想我会问.我正在考虑在不同的度量测量之间实现某种自定义转换 - 例如将英寸转换为米和其他单位.

我正在考虑称为Unit的基类如下.注意:我没有放任何字段来容纳单位数量,例如2米,5英寸等等:

public abstract class Unit {
    protected string _name;
    public Unit(string name)
    {
        _name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是仪表和英寸单位的子类:

public class Metre : Unit {
    public Metre() : base("Metre")
    {
    }
}

public class Inch : Unit {
    public Metre() : base("Inch")
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我想有一个班级可以处理这些单位之间的转换.就像是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Bro*_*ass 5

如果提前知道单位,则可以使用隐式转换运算符:

public class Metre : Unit 
{
    public Metre() : base("Metre")
    {
    }

    public static implicit operator Inch(Metre m)  
    { 
        return new Inch(39.37 * m.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)