拡張メソッドのサンプル(C#で使う)
文字列を整数に変換して、その合計を求める拡張メソッドのサンプルになります。
拡張メソッド
文字列配列の場合と文字列Listの場合に対応しています。(引数の型をIEnumerable<>にすることによって実現)
また、LINQを使って加算を繰り返し、結果を整数型の戻り値としています。
using System.Collections.Generic;
using System.Linq;
namespace Sample
{
    public static class Int
    {
        public static int ParseSum(this IEnumerable<string> str) => str.Select(s => int.Parse(s)).Sum();
    }
}
使い方
using System;
using System.Collections.Generic;
using System.Linq;
using Sample;
namespace MyNamespace
{
    class MyClass
    {
        public static void Main()
        {
            var str = new string[] { "1", "2", "3" };
            var sum = Int.ParseSum(str);
            Console.WriteLine(sum);
            var str2 = new List<string> { "4", "5", "6" };
            sum = Int.ParseSum(str2);
            Console.WriteLine(sum);
            var str3 = new List<string> { "7", "8", "9" };
            sum = ParseSum(str3);
            Console.WriteLine(sum);
        }
        static int ParseSum(List<string> str) => str.Select(s => int.Parse(s)).Sum();
    }
}
結果
6
15
24
参考
訪問数 24 回, 今日の訪問数 1回






ディスカッション
コメント一覧
まだ、コメントがありません