我正在寻找定义新类型并在 C# 中使用它的可能性,如下所示:
类定义:
public class Position
{
public double180 Longitude { get; set; } // double180 is a type within a range -180 and 180
public double90 Latitude { get; set; } // double90 is a type within a range of -90 and 90
}
用法:
var position = new Position
{
Longitude = 45,
Latitude = 96 // This line should give an error while initializing the object
};
最佳答案
你不一定需要一个新的类型。您可以手动编写一个验证值的 setter ,而不是使用自动属性:
public double Latitude
{
get
{
return mLatitude;
}
set
{
if (value > 90 || value < -90)
{
throw new ArgumentOutOfRangeException("Invalid latitude");
}
mLatitude = value;
}
}
private double mLatitude;
如果你想重用这段代码,你可以定义你自己的类型并在其中使用上面的setter;然后提供适当的构造函数和转换运算符。
关于c# - C# 中的新类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583800/