Is it possible to call method directly on object literals in C#?
In C#, when calling some instance methods, We always declare a variable of that typ开发者_开发技巧e, then assign a value to it, and call that method at last:
string str = "this is a string";
int test = str.IndexOf("a");
In Javascript, we can do this:
var test = 'sdfsldkfjskdf'.indexOf('a');
Is this kind of method calls legal in C#, say, directly use the string literal as a shorthand, without the declaration of a variable?
Yes, it's absolutely valid and fine.
I suspect you don't always declare a variable even without using literals. For example, consider:
string x = "hello";
string y = x.Substring(2, 3).Trim();
Here we're using the result of Substring
as the instance on which to call Trim
. No separate variable is used.
But this could equally have been written:
string y = "hello".Substring(2, 3).Trim();
The same is true for primitive literals too:
string x = 12.ToString("0000");
Ultimately, a literal is just another kind of expression, which can be used as the target of calls to instance methods.
Yes it is possible. However I would not recommend it in general, because it is confusing, and not clear to other developers what you are doing.
Yes it's valid. No problem with it.
Yes, and the best thing about it is that you don't even have to check for null.
精彩评论