Type Parameter Constraints - no generics (or nearest offer!)

折月煮酒 提交于 2019-12-10 23:11:50

问题


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.

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;
    }
}

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;
    }
}

Any thoughts?


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/8902428/type-parameter-constraints-no-generics-or-nearest-offer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!