使用c#,当我有一个对象类型的变量时,如何利用可空值的类型?
例如,我在一个类中有一个方法Insert,它有4个参数:
public int Update(Int32 serial, object deliveryDate, object quantity, object shiftTime)
{
....
....
....
}
Run Code Online (Sandbox Code Playgroud)
您可以猜到,此方法会在表中插入新记录.表(Table1)有4个列:Serial int,DeliveryDate DateTime null,Quantity float not null和ShiftTime smallint null
现在,我的问题是:我如何利用可空的值类型,并且我可以将对象转换为我想要的类型,如DateTime?
谢谢
为什么你的类型对象的参数首先?为什么不呢:
public int Update(int serial, DateTime? deliveryDate,
double? quantity, short? shiftTime)
Run Code Online (Sandbox Code Playgroud)
(注意,这decimal可能是一个更好的选择double- 需要考虑的事情.)
如果您可以更改方法签名,那可能就是这样.
否则,你在问题中真正提出的是什么?如果你不能改变参数,但是参数应该是type DateTime(或null),double(或null)和short(或null),那么你可以将它们转换为可空的等价物.这将取消null设置为该类型的空值,并将非空值设置为相应的非空值:
object x = 10;
int? y = (int?) x; // y = non-null value 10
x = null;
y = (int?) x; // y is null value of the Nullable<int> type
Run Code Online (Sandbox Code Playgroud)
编辑:回复评论......
假设您有一个移位时间的文本框.有三个选项:它填写但不恰当(例如"foo"),它是空的,或者它是有效的.你会做这样的事情:
short? shiftTime = null;
string userInput = shiftTimeInput.Text;
if (userInput.Length > 0) // User has put *something* in
{
short value;
if (short.TryParse(userInput, out value))
{
shiftTime = value;
}
else
{
// Do whatever you need to in order to handle invalid
// input.
}
}
// Now shiftTime is either null if the user left it blank, or the right value
// Call the Update method passing in shiftTime.
Run Code Online (Sandbox Code Playgroud)