- C#入門經典(第7版):C# 6.0 & Visual Studio 2015(.NET開發經典名著)
- (美)Beijamin Perkins Jacob Vibe Hammer Jon D. Reid
- 392字
- 2021-04-02 21:18:39
6.4 結構函數
第5章介紹了結構類型,它可在一個地方存儲多個數據元素,但實際上結構可以做的工作遠不止這一點。例如,除了數據,結構還可以包含函數。這初看起來很奇怪,但實際上是非常有用的。例如,考慮以下結構:
struct CustomerName { public string firstName, lastName; }
如果變量類型是CustomerName,并且要在控制臺上輸出一個完整的姓名,就必須使用姓、名構成該姓名。例如,對于CustomerName變量myCustomer,可以使用下述語法:
CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; WriteLine($"{myCustomer.firstName} {myCustomer.lastName}");
把函數添加到結構中,就可以集中處理常見任務,從而簡化這個過程。可以把合適的函數添加到結構類型中,如下所示:
struct CustomerName
{
public string firstName, lastName;
public string Name() => firstName + " " + lastName;
}
看起來這與本章前面的其他函數類似,只不過沒有使用static修飾符。本書后面將闡明其原因,現在知道該關鍵字不是結構函數所必需的即可。這個函數的用法如下所示:
CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; WriteLine(myCustomer.Name());
這個語法比前面的語法簡單得多,也更容易理解。注意,Name()函數可以直接訪問firstName和lastName結構成員。在customerName結構中,它們可以被看成全局成員。
推薦閱讀
- DevOps with Kubernetes
- Swift 3 New Features
- Internet of Things with the Arduino Yún
- 微信小程序項目開發實戰
- C語言程序設計
- Visual C#通用范例開發金典
- Python Data Analysis Cookbook
- Getting Started with Hazelcast(Second Edition)
- Python High Performance Programming
- Arduino Wearable Projects
- Clojure High Performance Programming(Second Edition)
- 深度學習的數學:使用Python語言
- Mastering Swift 4(Fourth Edition)
- FORTRAN程序設計權威指南
- ROS Robotics Projects