[英]How do you call a method using only some of its parameters?
我試圖將文本框中的字符串傳遞給同一類中的方法,但是當我嘗試這樣做時,卻收到錯誤消息:
no overload method, TotalWeighting takes one argument.
盡管在試圖發送給方法的參數中包含了每個對象。 錯誤消息出現在調用方法的位置。
這是程序的底部:
public void textBox7_TextChanged(object sender, EventArgs e)
{//Assignment 6, box 1
string STRtb11 = textBox7.Text;//Get value from textBox7 and set to new varaible STRtb10
TotalWeighting(STRtb11);
}
public void textBox12_TextChanged(object sender, EventArgs e)
{//Assignment 6, box 2
string STRtb12 = textBox12.Text;//Get value from textBox12 and set to new varaible STRtb11
TotalWeighting(STRtb12);
}
public static double TotalWeighting(string STRtb1, string STRtb2, string STRtb3, string STRtb4, string STRtb5, string STRtb6, string STRtb7, string STRtb8, string STRtb9, string STRtb10, string STRtb12)
{
return 0;
}
您的方法TotalWeighting
接受12個字符串,並且以當前形式不能接受其他任何內容。
有幾種方法可以改進此方法:
您可以為每個不使用的字符串傳遞null
,並在方法中處理這些null:
TotalWeighting("alpha", "bravo", null, null, null, null, null, null, null, null, null, null);
您可以通過將方法簽名更改為以下內容來使用默認參數:
public static double TotalWeighting( string STRtb1 = null, string STRtb2 = null, string STRtb3 = null, string STRtb4 = null, string STRtb5 = null, string STRtb6 = null, string STRtb7 = null, string STRtb8 = null, string STRtb9 = null, string STRtb10 = null, string STRtb12 = null) { return 0; }
您可以為每個所需數量的參數重載該方法:
public static double TotalWeighting(string STRtb1) { ... } public static double TotalWeighting(string STRtb1, string STRtb2) { ... } ...
您可以使用params關鍵字來允許該方法接受可變數量的參數:
public static double TotalWeighting(params string[] input) { ... }
你TotalWeighting
方法需要12個參數 STRtb1..STRtb12
; 因此,您應該提供以下12個參數,或者僅使用1個參數實現函數:
// Leave 1 argument of 12 ones
public static double TotalWeighting(string STRtb1) {
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.