今天在书上看到了段对于可空类型运用的代码 对于数学白痴的我 实在汗颜.....
被这段代码吸引不是对于可空类型的运用 而是里面有运算符重载 对 ToString() 的重写
觉得挺综合的 就打了下看看 唉 发现作为数学白痴的我 实在情何以堪.....
- class Vector
- {
- public double? R = null;
- public double? Theta = null;
- public double? ThetaRadians
- {
- get
- {
- return (Theta * Math.PI / 180.0);
- }
- }
- public Vector(double? r, double? theta)
- {
- if (r > 0)
- {
- r = -r;
- theta += 180;
- }
- theta = theta % 360;
- R = r;
- Theta = theta;
- }
- /// <summary>
- /// 重载+运算符
- /// </summary>
- /// <param name="op1"></param>
- /// <param name="op2"></param>
- /// <returns></returns>
- public static Vector operator +(Vector op1, Vector op2)
- {
- try
- {
- double newX = op1.R.Value * Math.Sin(op1.ThetaRadians.Value) + op2.R.Value * Math.Sin(op2.ThetaRadians.Value);
- double newY = op1.R.Value * Math.Cos(op1.ThetaRadians.Value) + op2.R.Value * Math.Cos(op2.ThetaRadians.Value);
- double newR = Math.Sqrt(newX * newX + newY * newY);
- double newTheta = Math.Atan2(newX, newY) * 180.0 / Math.PI;
- return new Vector(newR, newTheta);
- }
- catch
- {
- return new Vector(null,null);
- }
- }
- /// <summary>
- /// 重载-运算符
- /// </summary>
- /// <param name="op1"></param>
- /// <returns></returns>
- public static Vector operator -(Vector op1)
- {
- return new Vector(-op1.R, op1.Theta);
- }
- /// <summary>
- /// 重载-运算符
- /// </summary>
- /// <param name="op1"></param>
- /// <param name="op2"></param>
- /// <returns></returns>
- public static Vector operator -(Vector op1, Vector op2)
- {
- return op1 + (-op2);
- }
- /// <summary>
- /// 重写ToString()运算符
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- string rString = R.HasValue ? R.ToString() : "null";
- string thetaString = Theta.HasValue ? Theta.ToString() : "null";
- return string.Format("({0},{1})", rString, thetaString);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Vector v1 = GetVector("vector1");
- Vector v2 = GetVector("vector2");
- Console.WriteLine("{0} + {1} = {2}", v1, v2, v1 + v2);
- Console.WriteLine("{0} + {1} = {2}", v1, v2, v1 - v2);
- Console.ReadKey();
- }
- /// <summary>
- /// 输入值
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public static Vector GetVector(string name)
- {
- Console.WriteLine("输入{0}大小:", name);
- double? r = GetNullableDouble();
- Console.WriteLine("输入{0}角", name);
- double? theta = GetNullableDouble();
- return new Vector(r, theta);
- }
- /// <summary>
- /// 取值 如果无法转换为double型 则给空值
- /// 这里我对它用异常处理的方式感到不是特别好. 想用Double.TryParse取代 发现result定义的是可空类型
- /// 有什么办法可以用我的思路实现么 可是要是在TryParse之前强转下 把它设为可空类型就完全没有意义了
- /// </summary>
- /// <returns></returns>
- public static double? GetNullableDouble()
- {
- double? result;
- string userInput = Console.ReadLine();
- try
- {
- result = double.Parse(userInput);
- }
- catch
- {
- result = null;
- }
- return result;
- }
- }