c# 中的可空类型,今天记录了下c#中的可空类型,之前编写没有遇到过,而且之前c++中也没有这个概念,可能我学的是个假的c++吧,这个是泛型中的一个知识点,相当于c++中的模板,话不多说一起来看看吧。
?
int ? op1 = null;
int ? result = op1 *2 ?? 5;
如果没有系统学c#的看到这个会不会一脸的问号,还可以用?来写在这里??,那我们简单的分析一下吧,int ?相当于程序中的:
System.Nullable<int>
的缩写,说明变量可以是空变量。
??
是空接合运算符,是一个二元的运算符:
相当于:
op1 ?? op2
等价于
op1 = null ? op2 : op1;
下面我们来看一个例子:
首先的Vector 中的一个类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch12Ex01
{
public class Vector
{
public double? R = null;
public double? Theta = null;
public double? ThetaRadians
{
get
{
// Convert degrees to radians.
return (Theta * Math.PI / 180.0);
}
}
public Vector(double? r, double? theta)
{
// Normalize.
if (r < 0)
{
r = -r;
theta += 180;
}
theta = theta % 360;
// Assign fields.
R = r;
Theta = theta;
}
public static Vector operator +(Vector op1, Vector op2)
{
try
{
// Get (x, y) coordinates for new vector.
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);
// Convert to (r, theta).
double newR = Math.Sqrt(newX * newX + newY * newY);
double newTheta = Math.Atan2(newX, newY) * 180.0 / Math.PI;
// Return result.
return new Vector(newR, newTheta);
}
catch
{
// Return "null" vector.
return new Vector(null, null);
}
}
public static Vector operator -(Vector op1)
{
return new Vector(-op1.R, op1.Theta);
}
public static Vector operator -(Vector op1, Vector op2)
{
return op1 + (-op2);
}
public override string ToString()
{
// Get string representation of coordinates.
string rString = R.HasValue ? R.ToString() : "null";
string thetaString = Theta.HasValue ? Theta.ToString() : "null";
// Return (r, theta) string.
return string.Format("({0}, {1})", rString, thetaString);
}
}
}
主函数部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch12Ex01
{
class Program
{
static void Main(string[] args)
{
Vector v1 = GetVector("vector1");
Vector v2 = GetVector("vector1");
Console.WriteLine("{0} + {1} = {2}", v1, v2, v1 + v2);
Console.WriteLine("{0} - {1} = {2}", v1, v2, v1 - v2);
Console.ReadKey();
}
static Vector GetVector(string name)
{
Console.WriteLine("Input {0} magnitude:", name);
double? r = GetNullableDouble();
Console.WriteLine("Input {0} angle (in degrees):", name);
double? theta = GetNullableDouble();
return new Vector(r, theta);
}
static double? GetNullableDouble()
{
double? result;
string userInput = Console.ReadLine();
try
{
result = double.Parse(userInput);
}
catch
{
result = null;
}
return result;
}
}
}
就是这样的简单的,没有啥,慢慢来,c#不是那么难,还是慢慢一步一步来学习吧,我觉得要换一种学习方式了,一程序例子为主,一步一步去理解里面的东西。