开发者

Using c#, How can I take benefit of using nullable valuetypes when I have a variable of object type?

Using c#, How can I take 开发者_如何学JAVAbenefit of using nullable value types when I have a variable of object type?

For example, I have a method Insert within a class which takes 4 arguments:

public int Update(Int32 serial, object deliveryDate, object quantity, object shiftTime)
{
    ....
    ....
    ....
}

As you can guess, this method inserts a new record in a table. The table (Table1), has 4 colums: Serial int, DeliveryDate DateTime null, Quantity float not null and ShiftTime smallint null

Now, my quastion is : how can I take benefit of using nullable valuetypes and also ho can I convert object to my desirable types like DateTime?

Thank you


Why are your parameters of type object in the first place? Why isn't it:

public int Update(int serial, DateTime? deliveryDate,
                  double? quantity, short? shiftTime)

(Note that decimal may be a better choice than double - something to think about.)

If you can possibly change your method signature, that's probably the way to go.

Otherwise, what are you really asking in your question? If you can't change the parameters, but the arguments should be of type DateTime (or null), double (or null) and short (or null) then you can just cast them to their nullable equivalents. That will unbox null to the null value of the type, and non-null values to corresponding non-null values:

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

EDIT: To respond to the comment...

Suppose you have a text box for the shift time. There are three options: it's filled in but inappropriately (e.g. "foo"), it's empty, or it's valid. You'd do something like this:

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.


You may take a look at the System.Nullable<T> type. It has some shortcuts in C#:

public int Update(
    int serial, 
    DateTime? deliveryDate, 
    float? quantity, 
    short? shiftTime)

Which allows you to call method like this:

Update(10, null, null, null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜