我目前正在建立一个类库来处理单位度量,我想将工厂模式与静态方法一起使用来创建长度或面积等等。
要保持方法的一致性,我想创建一个接口或超类。有没有可能强制子类实现静态方法的方法?
(Offtopic:是否也可以强制子类来重载运算符?)
例如:
public class Length
{...
public static Length Create(double value, string unitCode)
{
var length = new Length();
switch (unitCode)
{
case "Mm":
length.Megameters = value;
break;
case "Km":
case "km":
length.Kilometers = value;
break;
case "hm":
length.Hectometers = value;
break;
case "dam":
length.Decameters = value;
break;
case "m":
length.Meters = value;
break;
case "dm":
length.Decimeters = value;
break;
case "cm":
length.Centimeters = value;
break;
case "mm":
length.Millimeters = value;
break;
case "µm":
length.Micrometers = value;
break;
case "pm":
length.Picometers = value;
break;
case "in":
length.Inches = value;
break;
case "ft":
length.Feet = value;
break;
case "yd":
length.Yards = value;
break;
case "mi":
length.Miles = value;
break;
case "smi":
length.ScandinavianMiles = value;
break;
case "ly":
length.LightYears = value;
break;
case "NM":
length.NauticalMiles = value;
break;
case "ftm":
length.Fathoms = value;
break;
case "fur":
length.Furlongs = value;
break;
case "ua":
length.AstronomicalUnits = value;
break;
case "pc":
length.Parsecs = value;
break;
default:
throw new ArgumentException("Not a valid unit given.", nameof(unitCode));
}
return length;
}
... }