- 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.
- 從零開始構建企業(yè)級RAG系統(tǒng)
- 程序員面試白皮書
- Java面向對象軟件開發(fā)
- OpenCV 3和Qt5計算機視覺應用開發(fā)
- 營銷數(shù)據(jù)科學:用R和Python進行預測分析的建模技術
- UML+OOPC嵌入式C語言開發(fā)精講
- Python Geospatial Development(Second Edition)
- 單片機應用技術
- Reactive Programming With Java 9
- QGIS:Becoming a GIS Power User
- Learning Python by Building Games
- Keras深度學習實戰(zhàn)
- Procedural Content Generation for C++ Game Development
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- Swift 4從零到精通iOS開發(fā)