What is the (type) in (type)objectname.var
I am going through a book on C# and have come across something that I can't 开发者_如何学JAVAseem to look up, because I don't know what it is called, or trying to search for something by description.
Could some explain to me what is going on, or the meaning behind the (type)
that comes before a reference to an object as in (int)objectname.variablename
?
It seems like casting to me.
EDIT: Since most of you are going off 'My' reference to casting when I am only guessing, and needed more code, I am including the code that I am reviewing that has brought on this question. I am questioning the (int) in the (int)numericupDown1.Value;
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
dinnerParty.NumberOfPeople = (int)numericUpDown1.Value;
DisplayDinnerPartyCost();
}
It is casting, it is trying to cast variablename into type (type) at runtime
It is casting(converting) the numericUpDown1.Value to an int value. This can also be done using
Convert.toInt32(numericUpDown1.Value)
I'm assuming that dinnerParty.NumberOfPeople is an integer value and therefore if you didn't cast it would throw an error if the value supplied was not an integer. For example if the Value supplied was a double or a string it would throw an error, with casting it would convert the double say 20.5 to 20 and it would be accepted. For the string it would depend on if the string contained a number in it. If the string was "12" then using the convert method mentioned above would convert it to the integer 12.
You're right. It is casting.
Without knowing the types involved it's hard to say exactly what is happening.
Casting will explicitly invoke the conversion operator from one type to another: http://msdn.microsoft.com/en-us/library/ms173105(VS.80).aspx
It could however be unboxing or explicit boxing. Boxing/Unboxing is an expensive way of storing value types on the heap. http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
As Eric Lippert (one of the designers of C#) mentioned in a comment elsewhere, this is Conversion - converting from one type to another.
It's not Casting. Casting is a leftover concept from C, where sometimes the compiler didn't know what type something was. The cast was a message to the compiler how to interpret the variable.
精彩评论