[英]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 type, then assign a value to it, and call that method at last: 在C#中,当调用某些实例方法时,我们总是声明该类型的变量,然后为其分配值,最后调用该方法:
string str = "this is a string";
int test = str.IndexOf("a");
In Javascript, we can do this: 在Javascript中,我们可以这样做:
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? 这种方法在C#中是否合法,例如,直接使用字符串文字作为速记方式,而无需声明变量?
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
. 在这里,我们将
Substring
的结果用作调用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.
没问题。
是的,关于它的最好的事情是您甚至不必检查null 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.