as string caused me a problem when dealing with object arrays. The values after execution are shown in the comments. Should it work this 开发者_开发百科way?
object[] array = new object[2];
array[0] = 0.33;
array[1] = "0.33";
string a = array[0] as string; // a == null !!!??????
string b = array[1] as string; // b == "0.33"
string a2 = array[0] == null ? "" : array[0].ToString(); // a2 == "0.33"
string a3 = Convert.ToString(array[0]); // a3 == "0.33"
Yes, it should.
as
is a cast operator.
It can only be used to cast an object to a type that it actually is (or a superclass thereof).
x as Y
returns null
if x
isn't a Y
.
the as-operator returns null when it fails to cast an object to the specified type. in this case it failed to cast 0.33 to type string, so string a is null.
MSDN:
The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception
So yes, the behaviour you are observing is correct.
The as operator is a casting operation, not a conversion operation, so it will only produce the value is the same type, or a super- or sub-class or the type you are trying to cast to.
(Unlike a regular cast, the as
operator also does not perform user-defined conversions using the operator
keyword.)
"as string" is not a synonym for "ToString()". You are using the "as" operator, and happened to pass it string as a type.
Definition of the as operator:
Remarks
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:
expression as type is equivalent to:
expression is type ? (type)expression : (type)null
The 'as' operator is basically like casting into a System.Type however the only difference is that it returns a null value if the cast fails instead of throwing an exception.
Check out this link for more info http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.71).aspx
array[0]
is a double
and cannot be casted to string
, hence null
.
Call ToString()
, most types override it to return something meaningful.
精彩评论