網站首頁 編程語言 正文
C#函數返回多個參數數值
通過out/Ref實現,聲明函數時用out指定返回變量。
- 寫了一個DEMO,輸入字符“測試字符”和數字6,返回“測試字符+新加字符”和666。
- 寫了一個窗體和button觸發函數,整理代碼如下,供大家參考。
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_Test_Click(object sender, EventArgs e) { //提前聲明返回參數變量 string str; int num; getValue("測試字符", 6,out str,out num);//調用函數返回數值 //輸出查看 Console.WriteLine("str:" + str + ";類型:" + str.GetType().ToString()); Console.WriteLine("num:" + num + ";類型:" + num.GetType().ToString()); } //定義測試函數 public void getValue(string in_str, int in_int, out string out_str, out int out_int) { out_str = in_str + "+新加字符"; out_int = in_int + 660;//函數結束一定給所有out對應變量賦值 } } }
輸出效果如下:
C#調用一個函數通過out返回多個變量值/數據
我們知道一個函數使用過Return來返回值的話只能返回一個值,在c#中,自定義一個函數時,用out 來out多個值出來,調用的時候就可以返回多個值
舉例
現在自己寫一個函數calculate(),需要返回加法和減法的計算結果,在主函數中輸出
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int c , d ; calculate(2, 3, out c,out d); Console.WriteLine(c); Console.WriteLine(d); Console.ReadLine(); } private static void calculate(int a, int b, out int c, out int d) { c = a + b; d = a - b; } } }
-
private
寫習慣了? -
static
?不想在主函數中再對calculate實例化 -
void
不要返回值 (第一次寫的時候掉了void 別掉)
也可以加返回值,比如,取返回值是bool型。比較a,b的值,如果a>b,輸出c,如果a<=b,則c不輸出,輸出“nothing”
static void Main(string[] args) { int c; if (calculate(2, 3, out c)) Console.WriteLine("c = "+c); else Console.WriteLine("Nothing"); Console.ReadLine(); } private static bool calculate(int a, int b, out int c) { bool t; if (a > b) t = true; else t = false; c = a - b; return t; }
輸出結果:
如果改變輸入 使得a= 3,b =2,則輸出結果:
總結
原文鏈接:https://blog.csdn.net/qq_38560619/article/details/107118285
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-09-21 go語言中的defer關鍵字_Golang
- 2022-11-15 Python+?Flask實現Mock?Server詳情_python
- 2022-10-03 C++虛函數表與類的內存分布深入分析理解_C 語言
- 2023-11-12 Check failed: top_shape[j] == bottom[i]->shape(j)
- 2022-04-10 新版Microsoft Edge關閉平滑滾動,類似chrome效果
- 2022-07-21 Python中直接賦值、淺拷貝和深拷貝的區別
- 2023-01-01 Golang反射修改變量值的操作代碼_Golang
- 2022-05-05 Python數據序列化之pickle模塊_python
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支