简体   繁体   English

是否可以直接在C#中的对象文字上调用方法?

[英]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.

相关问题 直接调用javascript function中的C#方法 - Call C# method in javascript function directly C#可以将对象附加到方法调用而不将其作为参数吗? - C# Possible to attach an Object to a method call without having it as a parameter? 在C#中,子类对象如何才能直接调用被覆盖的超类方法? - In C# how can a sub class object can directly call a super class method which is overridden? 可以确定方法是由派生类调用还是直接调用为自身? C# - Possible to determine if a method is called by a derived class or directly as itself? C# 是否可以通过方法名称调用C#委托 - Is it possible to call a C# delegate by method name C#MSIL调用方法并传递一个对象[] - C# MSIL call method and pass an object[] 使用对象发送方和EventArgs调用方法c# - Call method c# with object sender and EventArgs 将纯C#对象传递给C ++并在该对象上调用方法 - Pass plain C# object to C++ and call a method on that object 使用object []和object [] []作为参数的C#调用方法(params object [] []) - C# call method (params object[][]) with object[] and object[][] as parameters C#-自动将方法调用传递给具有相同签名的对象的方法 - C# - Automatically pass method call to method of object with same signature
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM