- C# 7 and .NET Core Cookbook
- Dirk Strauss
- 250字
- 2021-07-03 00:11:52
How it works...
The changes that C# 7.0 has made to out variables are not major. They are, however, a major convenience to those developers who use it often. So far in this chapter, we have seen the use of Tuples, pattern matching, and out variables. We can easily combine some of what we have learned to create something truly unique. Consider the use of extension methods, Tuples, and out variables. We can easily create an extension method called ToInt() that has the following implementation:
public static (string originalValue, int integerValue, bool isInteger) ToInt(this string stringValue)
{
var t = (original: stringValue, toIntegerValue: 0, isInt: false);
if (int.TryParse(stringValue, out var iValue))
{
t.toIntegerValue = iValue; t.isInt = true;
}
return t;
}
We create a Tuple literal that will be returned in the event of the TryParse returning false. If the TryParse is true, I set the t.toIntegerValue and t.isInt values. The code that calls the extension method looks as follows:
var (original, intVal, isInteger) = sValue.ToInt();
if (isInteger)
{
WriteLine($"{original} is a valid integer");
// Do something with intVal
}
When you run your console application, you will see that the output is exactly the same as before. This just illustrates the power of the new features in C# 7.0 when combined with each other. Throw some pattern matching into the mix, and we will have a very potent extension method. I'll leave you folks to play around with this some more. There is a lot to discover.
- Node.js+Webpack開(kāi)發(fā)實(shí)戰(zhàn)
- Three.js開(kāi)發(fā)指南:基于WebGL和HTML5在網(wǎng)頁(yè)上渲染3D圖形和動(dòng)畫(huà)(原書(shū)第3版)
- Visual C
- 大數(shù)據(jù)分析與應(yīng)用實(shí)戰(zhàn):統(tǒng)計(jì)機(jī)器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- Visual C#.NET Web應(yīng)用程序設(shè)計(jì)
- Citrix XenServer企業(yè)運(yùn)維實(shí)戰(zhàn)
- Visual Basic程序設(shè)計(jì)(第三版)
- Python趣味編程與精彩實(shí)例
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)指導(dǎo)
- 零基礎(chǔ)學(xué)C語(yǔ)言(第4版)
- DevOps 精要:業(yè)務(wù)視角
- 軟硬件綜合系統(tǒng)軟件需求建模及可靠性綜合試驗(yàn)、分析、評(píng)價(jià)技術(shù)
- Learning iOS Penetration Testing
- 現(xiàn)代JavaScript編程:經(jīng)典范例與實(shí)踐技巧
- Isomorphic JavaScript Web Development