[英]Pass variable behind method call as parameter
在問之前我不得不說我是 C# 的新手,只是想了解這是如何完成的。 而且我沒有通過谷歌搜索找到它,因為很難將其放入聲明中。
當它們作為參數調用時,如何獲取放在它們后面的 object / 變量的方法。 而不是將它們放入方法的大括號中。 就像著名的ToString()
一樣。 澄清更多,
我怎樣才能寫一個方法:
public void foo(Object before /* = the object behind */){
console.log(before);
}
我可以這樣使用:
object.foo();
而不是像這樣使用它:
foo(object);
如果有多種方法可以實現這一點,我很樂意全部了解。 謝謝你。
一種方法是該方法是class 或 struct method 。
另一種方式是擴展方法。 但是要理解它們,您應該首先閱讀第一個主題,因為顧名思義,這是它的擴展。
對於 Stack Overflow 的回答來說,課程的主題太寬泛了,你應該找到你最喜歡的媒介(現實生活中的老師、書籍、視頻)並了解它。 它是 C# 和許多其他語言的基礎。
所以我認為你想要的是 class。例如:
class Program {
void Foo(){
// this method belongs to class "Program"
}
class MyClass {
public void Foo(){
// this method belongs to class "MyClass"
}
}
int Main(string[] args){
// You can call this classes Foo() as so:
Foo();
// You can also create a new object of your nested class and call it's Foo():
var myInstantiatedClassObject = new MyClass();
myInstantiatedClassObject.Foo();
}
}
如果您希望擴展現有的 object,您可以這樣做(這將擴展現有的 object string
以為其提供名為StrCat
的方法):
public static class StringExtensions {
public static string StrCat(this string a, string b){
return $"{a}{b}";
}
}
然后您的字符串對象將具有該方法:
string myString = "hello"
myString = myString.StrCat(" world");
// myString would then be "hello world"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.