From 32dc523cf0965ac95604e88518ac26ea5fdf2f4e Mon Sep 17 00:00:00 2001 From: t-tanaka Date: Wed, 13 Apr 2016 02:40:14 +0900 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=9B=9E=E5=85=AC=E9=96=8B=E7=94=A8?= =?UTF-8?q?=E3=81=AE=E3=82=B5=E3=83=B3=E3=83=97=E3=83=AB=E3=82=B3=E3=83=BC?= =?UTF-8?q?=E3=83=89=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CSharp CheatSeet/10-1 Indexer.linq | 29 +++++++ .../11-1 UserDefinedOperator.linq | 32 ++++++++ .../12-1 InstanceConstructor.linq | 35 +++++++++ CSharp CheatSeet/12-2 StaticConstructor.linq | 21 +++++ CSharp CheatSeet/12-3 Destructor.linq | 18 +++++ CSharp CheatSeet/13-1 Struct.linq | 31 ++++++++ CSharp CheatSeet/14-1 Inheritance.linq | 43 +++++++++++ CSharp CheatSeet/14-2 Abstract.linq | 47 ++++++++++++ CSharp CheatSeet/14-3 Interface.linq | 49 ++++++++++++ CSharp CheatSeet/15-1 Enum.linq | 28 +++++++ CSharp CheatSeet/15-2 Flags.linq | 17 +++++ CSharp CheatSeet/16-1 Iterator.linq | 39 ++++++++++ CSharp CheatSeet/17-1 Exception.linq | 28 +++++++ CSharp CheatSeet/18-1 Resource.linq | 48 ++++++++++++ CSharp CheatSeet/19-1 Lambda.linq | 34 +++++++++ CSharp CheatSeet/2-1 Literal.linq | 33 ++++++++ CSharp CheatSeet/2-2 String.linq | 30 ++++++++ CSharp CheatSeet/2-3 StringInterpolation.linq | 12 +++ CSharp CheatSeet/2-4 Array.linq | 32 ++++++++ CSharp CheatSeet/20-1 Async.linq | 76 +++++++++++++++++++ CSharp CheatSeet/3-1 ArithmeticOperator.linq | 39 ++++++++++ CSharp CheatSeet/3-2 ShiftOperator.linq | 24 ++++++ CSharp CheatSeet/3-3 RelationalOperator.linq | 15 ++++ CSharp CheatSeet/3-4 EqualityOperator.linq | 15 ++++ CSharp CheatSeet/3-5 CastOperator_is_as.linq | 38 ++++++++++ .../3-6 ConditionalLogicalOperator.linq | 26 +++++++ ...itonalOperator_NullCoalescingOperator.linq | 20 +++++ .../3-8 NullConditionOperator.linq | 14 ++++ CSharp CheatSeet/3-9 NameOfOperator.linq | 14 ++++ CSharp CheatSeet/4-1 if.linq | 30 ++++++++ CSharp CheatSeet/4-2 Switch.linq | 36 +++++++++ CSharp CheatSeet/4-3 While_Do.linq | 20 +++++ CSharp CheatSeet/4-4 For_ForEach.linq | 37 +++++++++ CSharp CheatSeet/4-5 Break_Continue.linq | 18 +++++ CSharp CheatSeet/5-1 NameSpace.linq | 32 ++++++++ CSharp CheatSeet/5-2 Using.linq | 38 ++++++++++ CSharp CheatSeet/6-1 Class.linq | 33 ++++++++ CSharp CheatSeet/6-2 StaticClass.linq | 22 ++++++ CSharp CheatSeet/6-3 Partial.linq | 24 ++++++ CSharp CheatSeet/6-4 TypeParameter.linq | 71 +++++++++++++++++ CSharp CheatSeet/6-5 NestedType.linq | 43 +++++++++++ CSharp CheatSeet/7-1 Method.linq | 32 ++++++++ CSharp CheatSeet/7-2 Ref_Out.linq | 34 +++++++++ CSharp CheatSeet/7-3 ParameterArray.linq | 17 +++++ CSharp CheatSeet/7-4 DefaultArgument.linq | 14 ++++ CSharp CheatSeet/7-5 ExtensionMethod.linq | 17 +++++ CSharp CheatSeet/8-1 Property.linq | 32 ++++++++ CSharp CheatSeet/8-2 AutoProperty.linq | 32 ++++++++ CSharp CheatSeet/9-1 Event.linq | 60 +++++++++++++++ 49 files changed, 1529 insertions(+) create mode 100644 CSharp CheatSeet/10-1 Indexer.linq create mode 100644 CSharp CheatSeet/11-1 UserDefinedOperator.linq create mode 100644 CSharp CheatSeet/12-1 InstanceConstructor.linq create mode 100644 CSharp CheatSeet/12-2 StaticConstructor.linq create mode 100644 CSharp CheatSeet/12-3 Destructor.linq create mode 100644 CSharp CheatSeet/13-1 Struct.linq create mode 100644 CSharp CheatSeet/14-1 Inheritance.linq create mode 100644 CSharp CheatSeet/14-2 Abstract.linq create mode 100644 CSharp CheatSeet/14-3 Interface.linq create mode 100644 CSharp CheatSeet/15-1 Enum.linq create mode 100644 CSharp CheatSeet/15-2 Flags.linq create mode 100644 CSharp CheatSeet/16-1 Iterator.linq create mode 100644 CSharp CheatSeet/17-1 Exception.linq create mode 100644 CSharp CheatSeet/18-1 Resource.linq create mode 100644 CSharp CheatSeet/19-1 Lambda.linq create mode 100644 CSharp CheatSeet/2-1 Literal.linq create mode 100644 CSharp CheatSeet/2-2 String.linq create mode 100644 CSharp CheatSeet/2-3 StringInterpolation.linq create mode 100644 CSharp CheatSeet/2-4 Array.linq create mode 100644 CSharp CheatSeet/20-1 Async.linq create mode 100644 CSharp CheatSeet/3-1 ArithmeticOperator.linq create mode 100644 CSharp CheatSeet/3-2 ShiftOperator.linq create mode 100644 CSharp CheatSeet/3-3 RelationalOperator.linq create mode 100644 CSharp CheatSeet/3-4 EqualityOperator.linq create mode 100644 CSharp CheatSeet/3-5 CastOperator_is_as.linq create mode 100644 CSharp CheatSeet/3-6 ConditionalLogicalOperator.linq create mode 100644 CSharp CheatSeet/3-7 ConditonalOperator_NullCoalescingOperator.linq create mode 100644 CSharp CheatSeet/3-8 NullConditionOperator.linq create mode 100644 CSharp CheatSeet/3-9 NameOfOperator.linq create mode 100644 CSharp CheatSeet/4-1 if.linq create mode 100644 CSharp CheatSeet/4-2 Switch.linq create mode 100644 CSharp CheatSeet/4-3 While_Do.linq create mode 100644 CSharp CheatSeet/4-4 For_ForEach.linq create mode 100644 CSharp CheatSeet/4-5 Break_Continue.linq create mode 100644 CSharp CheatSeet/5-1 NameSpace.linq create mode 100644 CSharp CheatSeet/5-2 Using.linq create mode 100644 CSharp CheatSeet/6-1 Class.linq create mode 100644 CSharp CheatSeet/6-2 StaticClass.linq create mode 100644 CSharp CheatSeet/6-3 Partial.linq create mode 100644 CSharp CheatSeet/6-4 TypeParameter.linq create mode 100644 CSharp CheatSeet/6-5 NestedType.linq create mode 100644 CSharp CheatSeet/7-1 Method.linq create mode 100644 CSharp CheatSeet/7-2 Ref_Out.linq create mode 100644 CSharp CheatSeet/7-3 ParameterArray.linq create mode 100644 CSharp CheatSeet/7-4 DefaultArgument.linq create mode 100644 CSharp CheatSeet/7-5 ExtensionMethod.linq create mode 100644 CSharp CheatSeet/8-1 Property.linq create mode 100644 CSharp CheatSeet/8-2 AutoProperty.linq create mode 100644 CSharp CheatSeet/9-1 Event.linq diff --git a/CSharp CheatSeet/10-1 Indexer.linq b/CSharp CheatSeet/10-1 Indexer.linq new file mode 100644 index 0000000..735760d --- /dev/null +++ b/CSharp CheatSeet/10-1 Indexer.linq @@ -0,0 +1,29 @@ + + +void Main() +{ + var my = new MyClass(); + my[1] = 100; + my[1].Dump(); + my["test"].Dump(); +} + +public class MyClass +{ + private int[] array = new int[100]; + private Dictionary dict = new Dictionary(); + + public int this[int i] + { + get + { + return array[i]; + } + set + { + array[i] = value; + } + } + + public int this[string s] => dict.ContainsKey(s) ? dict[s] : 0; +} \ No newline at end of file diff --git a/CSharp CheatSeet/11-1 UserDefinedOperator.linq b/CSharp CheatSeet/11-1 UserDefinedOperator.linq new file mode 100644 index 0000000..1d0ebb9 --- /dev/null +++ b/CSharp CheatSeet/11-1 UserDefinedOperator.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + var c1 = new Complex(1, 3) + new Complex(2, 4); // 3 + 7i + c1.Dump(); + + var c2 = -new Complex(2, -2); //-2+2i + c2.Dump(); +} + +public class Complex +{ + public double Real { get; } + public double Imaginary { get; } + + public Complex(double real, double imaginary) + { + Real = real; + Imaginary = imaginary; + } + + public static Complex operator -(Complex c1) + { + return new Complex(-c1.Real, -c1.Imaginary); + } + + public static Complex operator +(Complex c1, Complex c2) + { + return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/12-1 InstanceConstructor.linq b/CSharp CheatSeet/12-1 InstanceConstructor.linq new file mode 100644 index 0000000..2c7b8dd --- /dev/null +++ b/CSharp CheatSeet/12-1 InstanceConstructor.linq @@ -0,0 +1,35 @@ + + +void Main() +{ + var my1 = new MyClass(); + //0 + my1.Value.Dump(); + + var my2 = new MyClass(2); + //2 + my2.Value.Dump(); +} + +public class MyClass +{ + public int Value { get; set; } + + public MyClass() : this(0) + {} + + public MyClass(int v) + { + Value = v; + } + +} + +//singletonパターンなど、コンストラクタ呼び出しを公開したくない場合はprivateにできる +public class MyClass2 +{ + public static MyClass2 Instance = new MyClass2(); + + private MyClass2() + {} +} diff --git a/CSharp CheatSeet/12-2 StaticConstructor.linq b/CSharp CheatSeet/12-2 StaticConstructor.linq new file mode 100644 index 0000000..d3f2862 --- /dev/null +++ b/CSharp CheatSeet/12-2 StaticConstructor.linq @@ -0,0 +1,21 @@ + + +void Main() +{ + var my = new MyClass(); + //5 + my.Value.Dump(); +} + +public class MyClass +{ + static int DefaultValue; + static MyClass() + { + //代入するだけであればフィールドの初期化子として書けるが + //より複雑な初期化も可能 + DefaultValue = 5; + } + + public int Value { get; set; } = DefaultValue; +} \ No newline at end of file diff --git a/CSharp CheatSeet/12-3 Destructor.linq b/CSharp CheatSeet/12-3 Destructor.linq new file mode 100644 index 0000000..8d5f190 --- /dev/null +++ b/CSharp CheatSeet/12-3 Destructor.linq @@ -0,0 +1,18 @@ + + +void Main() +{ + var my = new MyClass(); + my = null; + GC.Collect(); + GC.WaitForPendingFinalizers(); // Destruct +} + +public class MyClass +{ + // デストラクター + ~MyClass() + { + Console.WriteLine("Destruct"); + } +} diff --git a/CSharp CheatSeet/13-1 Struct.linq b/CSharp CheatSeet/13-1 Struct.linq new file mode 100644 index 0000000..5d49177 --- /dev/null +++ b/CSharp CheatSeet/13-1 Struct.linq @@ -0,0 +1,31 @@ + + +void Main() +{ + var p1 = new Point(10); + //参照ではなく、コピーした値がp2に割り当てられる + var p2 = p1; + //p1のプロパティを更新してもp2には影響がない + p1.X = 1; + p1.Dump(); //p1.X=1 + p2.Dump(); //p2.X=10 + + //構造体をデフォルト値はnullではない + var points = new Point[10]; + //point[0].X=0 + points[0].Dump(); +} + +struct Point +{ + private int x; + public int X + { + get { return x; } + set { x = value; } + } + public Point(int x) + { + this.x = x; + } +} diff --git a/CSharp CheatSeet/14-1 Inheritance.linq b/CSharp CheatSeet/14-1 Inheritance.linq new file mode 100644 index 0000000..7875a66 --- /dev/null +++ b/CSharp CheatSeet/14-1 Inheritance.linq @@ -0,0 +1,43 @@ + + +void Main() +{ + var my = new MyClass1(); + my.Test2(); //MyClass1.Test2 + + var my2 = new MyClass2(); + my2.Test2(); //1 +} + +public class MyBase +{ + public int Value { get; set; } = 0; + + public void Test1() + { + Console.WriteLine("MyBase.Test1"); + } + + public virtual void Test2() + { + Console.WriteLine("MyBase.Test2"); + } +} + +public class MyClass1 : MyBase +{ + public new int Value { get; set; } = 1; + + public override void Test2() + { + Console.WriteLine("MyClass1.Test2"); + } +} + +public class MyClass2 : MyClass1 +{ + public override void Test2() + { + Console.WriteLine(Value); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/14-2 Abstract.linq b/CSharp CheatSeet/14-2 Abstract.linq new file mode 100644 index 0000000..9e0f78a --- /dev/null +++ b/CSharp CheatSeet/14-2 Abstract.linq @@ -0,0 +1,47 @@ + + +void Main() +{ + var my = new MyClass(); + my.Test1(); // MyAbstractClass.Test1 + my.Test2(); // MyClass.Test2 + my.Test3(); // MyClass.Test3 + + var my2 = new MyClass2(); + my2.Test1(); // MyAbstractClass.Test1 + my2.Test2(); // MyClass2.Test2 + my2.Test3(); // MyClass.Test3 +} + +public abstract class MyAbstractClass +{ + public void Test1() + { + Console.WriteLine("MyAbstractClass.Test1"); + } + + public abstract void Test2(); + + public abstract void Test3(); +} + +public class MyClass : MyAbstractClass +{ + public override void Test2() + { + Console.WriteLine("MyClass.Test2"); + } + + public sealed override void Test3() + { + Console.WriteLine("MyClass.Test3"); + } +} + +public sealed class MyClass2 : MyClass +{ + public override void Test2() + { + Console.WriteLine("MyClass2.Test2"); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/14-3 Interface.linq b/CSharp CheatSeet/14-3 Interface.linq new file mode 100644 index 0000000..3f9a8a9 --- /dev/null +++ b/CSharp CheatSeet/14-3 Interface.linq @@ -0,0 +1,49 @@ + + +void Main() +{ + var s1 = new Surface(); + s1.Name = "a"; + s1.Paint(); // Paint + ((ISurface)s1).Paint(); // Paint + ((IPaintable)s1).Paint(); // Paint + + var s2 = new Surface2(); + s2.Paint(); // Paint + ((ISurface)s2).Paint(); // Paint + ((IPaintable)s2).Paint(); // IPaintable.Paint +} + +interface IPaintable +{ + void Paint(); +} + +interface ISurface +{ + string Name { get; set; } + void Paint(); +} + +public class Surface : ISurface, IPaintable +{ + public string Name { get; set; } + public void Paint() + { + Console.WriteLine("Paint"); + } +} + +public class Surface2 : ISurface, IPaintable +{ + public string Name { get; set; } + public void Paint() + { + Console.WriteLine("Paint"); + } + + void IPaintable.Paint() + { + Console.WriteLine("IPaintable.Paint"); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/15-1 Enum.linq b/CSharp CheatSeet/15-1 Enum.linq new file mode 100644 index 0000000..e941521 --- /dev/null +++ b/CSharp CheatSeet/15-1 Enum.linq @@ -0,0 +1,28 @@ + + +void Main() +{ + var t1 = Color.Red; + t1.Dump(); + + var t2 = Color.Blue; + t2.Dump(); + + //定義されていない値をキャストすることが可能だが、非推奨 + var t3 = (LongType)23; + t3.Dump(); +} + +public enum Color +{ + Red, + Blue, + Orange +} + +public enum LongType : long +{ + Solid = int.MaxValue + 1L, + Soft = 1, + Hard = Solid +} \ No newline at end of file diff --git a/CSharp CheatSeet/15-2 Flags.linq b/CSharp CheatSeet/15-2 Flags.linq new file mode 100644 index 0000000..a367cb1 --- /dev/null +++ b/CSharp CheatSeet/15-2 Flags.linq @@ -0,0 +1,17 @@ + + +void Main() +{ + var colors = Color.Red | Color.Blue; + colors.HasFlag(Color.Red).Dump(); //True + (colors == Color.Red).Dump(); // False + colors.HasFlag(Color.Yellow).Dump(); // False +} + +[Flags] +public enum Color +{ + Red, + Blue, + Yellow +} diff --git a/CSharp CheatSeet/16-1 Iterator.linq b/CSharp CheatSeet/16-1 Iterator.linq new file mode 100644 index 0000000..4e45df9 --- /dev/null +++ b/CSharp CheatSeet/16-1 Iterator.linq @@ -0,0 +1,39 @@ + + +void Main() +{ + //a b c z + MyCollection.GetSamples().Dump(); + //1, 9, 25, 49, 81 + foreach (var element in new MyCollection()) + { + Console.WriteLine(element); + } +} + +public class MyCollection : IEnumerable +{ + public static IEnumerable GetSamples() + { + yield return "a"; + yield return "b"; + yield return "c"; + yield return "z"; + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < 10; i++) + { + if (i % 2 == 0) + continue; + + yield return i * i; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/17-1 Exception.linq b/CSharp CheatSeet/17-1 Exception.linq new file mode 100644 index 0000000..5f0f278 --- /dev/null +++ b/CSharp CheatSeet/17-1 Exception.linq @@ -0,0 +1,28 @@ + + +void Main() +{ + try + { + ThrowException(); + } + catch (MyException ex) when (ex.Value >= 1) + { + Console.WriteLine("Catch MyException"); + } + catch (Exception ex) + { + Console.WriteLine("Catch Exception: " + ex.Message); + throw; // 再スロー + } +} + +void ThrowException() +{ + throw new MyException() {Value = 1}; +} + +public class MyException : Exception +{ + public int Value { get; set; } +} \ No newline at end of file diff --git a/CSharp CheatSeet/18-1 Resource.linq b/CSharp CheatSeet/18-1 Resource.linq new file mode 100644 index 0000000..f9c688d --- /dev/null +++ b/CSharp CheatSeet/18-1 Resource.linq @@ -0,0 +1,48 @@ + + +void Main() +{ + var resource = new MyResource(); + try + { + resource.Execute(); + } + finally + { + resource.Close(); + } + + using (var r1 = new MyDisposableResource()) + using (var r2 = new MyDisposableResource()) + { + r1.Execute(); + r2.Execute(); + } +} + +public class MyResource +{ + public void Execute() + { + Console.WriteLine("MyResource.Execute"); + } + + public void Close() + { + Console.WriteLine("MyResource.Close"); + } +} + +public class MyDisposableResource : IDisposable +{ + public void Execute() + { + Console.WriteLine("MyDisposableResource.Execute"); + } + + public void Dispose() + { + Console.WriteLine("MyDisposableResource.Dispose"); + } +} + diff --git a/CSharp CheatSeet/19-1 Lambda.linq b/CSharp CheatSeet/19-1 Lambda.linq new file mode 100644 index 0000000..ee65c8c --- /dev/null +++ b/CSharp CheatSeet/19-1 Lambda.linq @@ -0,0 +1,34 @@ + + +void Main() +{ + Action a1 = () => + { + Console.WriteLine("Action"); + }; + //Action + a1(); + Action a2 = i => Console.WriteLine(i); + //2 + a2(2); + + Func f1 = () => 1; + //1 + f1().Dump(); + Func f2 = (s1, s2) => int.Parse(s1 + s2); + //54 + f2.Invoke("5", "4").Dump(); + + //LINQ + //9,1 + new[] {1, 3, 5} + .Where(i => i <= 3) + .Select(i => i * i) + .OrderByDescending(i => i) + .Dump(); + + //イベント + Changed += (s, ea) => {Console.WriteLine("OnChanged");}; +} + +event EventHandler Changed; diff --git a/CSharp CheatSeet/2-1 Literal.linq b/CSharp CheatSeet/2-1 Literal.linq new file mode 100644 index 0000000..340f6dc --- /dev/null +++ b/CSharp CheatSeet/2-1 Literal.linq @@ -0,0 +1,33 @@ + + +void Main() +{ + //bool型 + var flg1 = true; + var flg2 = false; + + //int, uint, long, ulong のうち表現できる最初の型。この場合はint型 + var int1 = 1; + //uまたはUサフィックスを付けた場合はuintもしくはulongのうち表現できる最初の型。この場合はuint型 + var int2 = 1U; + //lまたはLサフィックスを付けた場合はlongもしくはulongのうち表現できる最初の型。この場合はuint型 + var int3 = 1L; + //ulもしくはULサフィックスを付けた場合はulong型 + var int4 = 1UL; + + //単精度浮動小数点 + var number1 = 1f; + //指数表記 + var number2 = 1.2e-3f; + //倍精度浮動小数点 + var number3 = 1d; + //指数表記 + var number4 = 1.2e-3d; + //高精度小数(decimal型) + var number5 = 0.1m; + + var char1 = '1'; + var char2 = '\''; + var char3 = '\xFFFF'; + char2.Dump(); +} diff --git a/CSharp CheatSeet/2-2 String.linq b/CSharp CheatSeet/2-2 String.linq new file mode 100644 index 0000000..84a521b --- /dev/null +++ b/CSharp CheatSeet/2-2 String.linq @@ -0,0 +1,30 @@ + + +void Main() +{ + var str01 = "Hello World"; + str01.Dump(); + var str02 = @"Hello World"; + str02.Dump(); + + var str03 = "Hello \t World"; // Hello World + str03.Dump(); + var str04 = @"Hello \t World"; // Hello \t World + str04.Dump(); + + var str05 = "\"Hello\" World"; // "Hello" World + str05.Dump(); + var str06 = @"""Hello"" World"; // "Hello" World + str06.Dump(); + + var str07 = "C:\\tmp\\log.txt"; // C:\tmp\log.txt + str07.Dump(); + var str08 = @"C:\tmp\log.txt"; // C:\tmp\log.txt + str08.Dump(); + + var str09 = "Hello\r\nWorld"; + str09.Dump(); + var str10 = @"Hello +World"; + str10.Dump(); +} \ No newline at end of file diff --git a/CSharp CheatSeet/2-3 StringInterpolation.linq b/CSharp CheatSeet/2-3 StringInterpolation.linq new file mode 100644 index 0000000..92151a1 --- /dev/null +++ b/CSharp CheatSeet/2-3 StringInterpolation.linq @@ -0,0 +1,12 @@ + + +void Main() +{ + var name = "テスト"; + var s1 = $@"名前は +{name}"; + s1.Dump(); + + var s2 = $"Now: {DateTime.Now :f}"; + s2.Dump(); +} \ No newline at end of file diff --git a/CSharp CheatSeet/2-4 Array.linq b/CSharp CheatSeet/2-4 Array.linq new file mode 100644 index 0000000..885253d --- /dev/null +++ b/CSharp CheatSeet/2-4 Array.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + //要素数を指定して配列を初期化 + var array1 = new int[2]; + array1.Dump(); + array1[1].Dump(); // 0 (intのデフォルト値) + + //要素を指定して配列を初期化 + var array2 = new[] { 1, 2, 3 }; + array2.Dump(); + + //プロパティ、フィールドなど左辺に型を記述する場合、new[] は不要 + double[] array3 = { 1d, 2.3d }; + array3.Dump(); + + //配列は IList を実装している + IList list3 = new[] { "A", "B" }; + list3.Dump(); + + //2次元配列 + var array5 = new[,] { { 1, 2 }, { 3, 4 }}; + array5.Dump(); + array5[1,0].Dump(); + + //配列の配列 + var array6 = new[] { new[] { 1, 3, 5 }, new[] { 2, 4, 6, 8 }}; + array6.Dump(); + array6[1][3].Dump(); +} + diff --git a/CSharp CheatSeet/20-1 Async.linq b/CSharp CheatSeet/20-1 Async.linq new file mode 100644 index 0000000..52554c7 --- /dev/null +++ b/CSharp CheatSeet/20-1 Async.linq @@ -0,0 +1,76 @@ + + System.Threading.Tasks + + +void Main() +{ + //Mainメソッドはasyncにできない + //非同期メソッドを同期的に待機する場合、GetAwaiter().GetResult() が使える + ExecuteAsync().GetAwaiter().GetResult(); +} + +static async Task ExecuteAsync() +{ + var sw = Stopwatch.StartNew(); + //2秒待機 + await TestAsync(); + sw.Stop(); + //await: 2 [sec] + Console.WriteLine($"await: {sw.Elapsed.Seconds} [sec]"); + sw.Restart(); + //この時点では待機しない + var task = TestAsync(); + //未await: 0 [sec] + Console.WriteLine($"未await: {sw.Elapsed.Seconds} [sec]"); + await task; + //await: 2 [sec] + Console.WriteLine($"await: {sw.Elapsed.Seconds} [sec]"); + sw.Restart(); + //一度完了したTaskをawaitすると、すぐに完了する + await task; + //再await: 0 [sec] + Console.WriteLine($"再await: {sw.Elapsed.Seconds} [sec]"); + + var task2 = TestAsync(); + sw.Restart(); + + sw.Restart(); + //async void メソッドを呼んでも待機しない + VoidAsync(); + //async void: 0 [sec] + Console.WriteLine($"async void: {sw.Elapsed.Seconds} [sec]"); + + sw.Restart(); + var r1 = await TestAsync2(); + //await Task: Result=1 2 [sec] + Console.WriteLine($"await Task: Result={r1} {sw.Elapsed.Seconds} [sec]"); + + var t2 = TestAsync2(); + sw.Restart(); + //Task のResultプロパティで結果を取得できるが、プロパティアクセスで待機することになる + var r2 = t2.Result; + //Get Task.Result: Result=1 2 [sec] + Console.WriteLine($"Get Task.Result: Result={r2} {sw.Elapsed.Seconds} [sec]"); + + sw.Restart(); + //await同様、一度完了したTaskのResultプロパティは待機せずに取得できる + var r3 = t2.Result; + //Get Task.Result again: Result=1 0 [sec] + Console.WriteLine($"Get Task.Result again: Result={r3} {sw.Elapsed.Seconds} [sec]"); +} + +static async Task TestAsync() +{ + await Task.Delay(TimeSpan.FromSeconds(2)); +} + +static async void VoidAsync() +{ + await Task.Delay(TimeSpan.FromSeconds(2)); +} + +static async Task TestAsync2() +{ + await Task.Delay(TimeSpan.FromSeconds(2)); + return 1; +} \ No newline at end of file diff --git a/CSharp CheatSeet/3-1 ArithmeticOperator.linq b/CSharp CheatSeet/3-1 ArithmeticOperator.linq new file mode 100644 index 0000000..4026e1e --- /dev/null +++ b/CSharp CheatSeet/3-1 ArithmeticOperator.linq @@ -0,0 +1,39 @@ + + +void Main() +{ + //加算 + var x0 = 1 + 4; // 5 + x0.Dump(); + //int + double は double + doubleとして加算。結果もdouble + var x1 = 1 + 2.5d; // = 3.5 + x1.Dump(); + //int - long は long - long + var x2 = int.MinValue - 1L; // = -2147483649 + x2.Dump(); + //乗算 + var x3 = 2 * 4; // = 8 + x3.Dump(); + //uncheckedコンテキストではオーバーフローしても処理が続行される + //int.MaxValue * 2L だと 4294967294L + unchecked + { + var x4 = int.MaxValue * 2; // = -2 + x4.Dump(); + } + //整数の除算は演算結果も整数 + var x5 = 7 / 2; // = 3 + x5.Dump(); + //割られる数がdoubleであれば演算結果もdoubleになる + var x6 = 7f / 2; // = 3.5 + x6.Dump(); + //割る数がdoubleの場合もdouble型の除算が行われる + var x7 = 7 / 2.0; // = 3.5 + x7.Dump(); + //剰余 + var x8 = 7 % 2; // = 1 + x8.Dump(); + //浮動小数点 + var x9 = 7f % 2.1; // = 0.7 + x9.Dump(); +} \ No newline at end of file diff --git a/CSharp CheatSeet/3-2 ShiftOperator.linq b/CSharp CheatSeet/3-2 ShiftOperator.linq new file mode 100644 index 0000000..70e8be9 --- /dev/null +++ b/CSharp CheatSeet/3-2 ShiftOperator.linq @@ -0,0 +1,24 @@ + + +void Main() +{ + // 0001 << 00001 = 0010 + var x0 = 1 << 1; //2 + x0.Dump(); + // 33 = 0010 0001 だが下位5ビットをシフトカウントとして使うため、 00001 でシフトする + // 0001 << 00001 = 0010 + var x1 = 1 << 33; //2 + x1.Dump(); + // longまたはulongのときは下位6ビットでシフトする + // 0001 << 100001 + var x2 = 1L << 33; //8589934592 + x2.Dump(); + // 97 = 0110 0001 の下位6ビットでシフトする + // 0001 << 100001 + var x3 = 1L << 97; //8589934592 + x3.Dump(); + + // 0011 1110 1000 >> 3 = 125 (0111 1101) + var x4 = 1000 >> 3; //125 + x4.Dump(); +} diff --git a/CSharp CheatSeet/3-3 RelationalOperator.linq b/CSharp CheatSeet/3-3 RelationalOperator.linq new file mode 100644 index 0000000..53b7947 --- /dev/null +++ b/CSharp CheatSeet/3-3 RelationalOperator.linq @@ -0,0 +1,15 @@ + + +void Main() +{ + var f1 = 1 > 1; // False + f1.Dump(); + var f2 = 1 >= 1; // True + f2.Dump(); + var f3 = 1 < 2; // True + f3.Dump(); + var f4 = 1 <= 2; // True + f4.Dump(); +} + +// Define other methods and classes here diff --git a/CSharp CheatSeet/3-4 EqualityOperator.linq b/CSharp CheatSeet/3-4 EqualityOperator.linq new file mode 100644 index 0000000..2e6eb6c --- /dev/null +++ b/CSharp CheatSeet/3-4 EqualityOperator.linq @@ -0,0 +1,15 @@ + + +void Main() +{ + var f1 = 1 == 2; //False + f1.Dump(); + var f2 = 1 != 1; //False + f2.Dump(); + var f3 = new object() == new object(); //False + f3.Dump(); + var f4 = "abc" == string.Copy("a") + "bc"; //True + f4.Dump(); +} + +// Define other methods and classes here \ No newline at end of file diff --git a/CSharp CheatSeet/3-5 CastOperator_is_as.linq b/CSharp CheatSeet/3-5 CastOperator_is_as.linq new file mode 100644 index 0000000..079a5e7 --- /dev/null +++ b/CSharp CheatSeet/3-5 CastOperator_is_as.linq @@ -0,0 +1,38 @@ + + +void Main() +{ + var b = new B(); + var c = new C(); + + var f0 = b is B; //True + f0.Dump(); + var f1 = b is A; //True + f1.Dump(); + var f2 = c is A; //False + f2.Dump(); + + //A型の変数として宣言 + A a = new B(); + + // is で型チェック後キャストする + if (a is B) + { + ((B)a).Test(); //I'm B + } + + //is+キャストはas+nullチェックで代用可能。 + //なお、asの方が効率的なコードをコンパイラが出力する + var b2 = a as B; + if (b2 != null) + { + b2.Test(); //I'm B + } + + //nullチェックはnull条件演算子で置き換えることも可能 + (a as B)?.Test(); //I'm B +} + +class A { } +class B : A { public void Test() { Console.WriteLine("I'm B."); } } +class C { } \ No newline at end of file diff --git a/CSharp CheatSeet/3-6 ConditionalLogicalOperator.linq b/CSharp CheatSeet/3-6 ConditionalLogicalOperator.linq new file mode 100644 index 0000000..e1a87b2 --- /dev/null +++ b/CSharp CheatSeet/3-6 ConditionalLogicalOperator.linq @@ -0,0 +1,26 @@ + + +void Main() +{ + var f1 = True() || False(); //True is called: True + f1.Dump(); + var f2 = True() | False(); // True is called: False is called: True + f2.Dump(); + + var f3 = False() && True(); // False is called: False + f3.Dump(); + var f4 = False() & True(); // False is called: True is called: False + f4.Dump(); +} + +static bool True() +{ + Console.Write("True is called: "); + return true; +} + +static bool False() +{ + Console.Write("False is called: "); + return false; +} \ No newline at end of file diff --git a/CSharp CheatSeet/3-7 ConditonalOperator_NullCoalescingOperator.linq b/CSharp CheatSeet/3-7 ConditonalOperator_NullCoalescingOperator.linq new file mode 100644 index 0000000..93e7962 --- /dev/null +++ b/CSharp CheatSeet/3-7 ConditonalOperator_NullCoalescingOperator.linq @@ -0,0 +1,20 @@ + + +void Main() +{ + var f1 = true; + var t1 = f1 ? "true" : "false"; //true + t1.Dump(); + + var f2 = false; + var t2 = f2 ? "true" : "false"; //false + t2.Dump(); + + string v1 = null; + var t3 = v1 ?? "default"; //default + t3.Dump(); + + string v2 = "text"; + var t4 = v2 ?? "default"; //text + t4.Dump(); +} \ No newline at end of file diff --git a/CSharp CheatSeet/3-8 NullConditionOperator.linq b/CSharp CheatSeet/3-8 NullConditionOperator.linq new file mode 100644 index 0000000..04b7c0d --- /dev/null +++ b/CSharp CheatSeet/3-8 NullConditionOperator.linq @@ -0,0 +1,14 @@ + + +void Main() +{ + string[] array = null; + var length = array?.Length; //null + length.Dump(); + var i1 = array?[1]; //null。i1は int?型 + i1.Dump(); + + Func func = null; + var i2 = func?.Invoke(); //null。i2は int?型 + i2.Dump(); +} diff --git a/CSharp CheatSeet/3-9 NameOfOperator.linq b/CSharp CheatSeet/3-9 NameOfOperator.linq new file mode 100644 index 0000000..5fc020a --- /dev/null +++ b/CSharp CheatSeet/3-9 NameOfOperator.linq @@ -0,0 +1,14 @@ + + +void Main(string args) +{ + var s1 = nameof(args); //args + s1.Dump(); + + var s2 = nameof(DateTime.Now); //Now + s2.Dump(); + + var s3 = nameof(System.Linq); //Linq + s3.Dump(); +} + diff --git a/CSharp CheatSeet/4-1 if.linq b/CSharp CheatSeet/4-1 if.linq new file mode 100644 index 0000000..01190af --- /dev/null +++ b/CSharp CheatSeet/4-1 if.linq @@ -0,0 +1,30 @@ + + +void Main() +{ + var flg = true; + //true + if (flg) + Console.WriteLine("true"); + + //else if + if (Check()) + { + Console.WriteLine("if"); + } + else if (flg) + { + Console.WriteLine("else if"); + } + else + { + Console.WriteLine("else"); + } +} + +static bool Check() +{ + return false; +} + +// Define other methods and classes here \ No newline at end of file diff --git a/CSharp CheatSeet/4-2 Switch.linq b/CSharp CheatSeet/4-2 Switch.linq new file mode 100644 index 0000000..23b1502 --- /dev/null +++ b/CSharp CheatSeet/4-2 Switch.linq @@ -0,0 +1,36 @@ + + + void Main() +{ + var dayOfWeek = DayOfWeek.Thursday; + string text; + switch (dayOfWeek) + { + case DayOfWeek.Monday: + text = "月"; + break; + case DayOfWeek.Tuesday: + text = "火"; + break; + case DayOfWeek.Wednesday: + text = "水"; + break; + case DayOfWeek.Thursday: + text = "木"; + break; + case DayOfWeek.Friday: + text = "金"; + break; + case DayOfWeek.Saturday: + text = "土"; + break; + case DayOfWeek.Sunday: + text = "日"; + break; + default: + throw new ArgumentOutOfRangeException(); + } + text.Dump(); + //なお、日付を表すDateTime型のインスタンスからカレントカルチャの曜日の省略名を得る場合はこのように書ける + $"{DateTime.Now:ddd}".Dump(); +} \ No newline at end of file diff --git a/CSharp CheatSeet/4-3 While_Do.linq b/CSharp CheatSeet/4-3 While_Do.linq new file mode 100644 index 0000000..e72e542 --- /dev/null +++ b/CSharp CheatSeet/4-3 While_Do.linq @@ -0,0 +1,20 @@ + + +void Main() +{ + int term = 0; + while (term <= 3) + { + Console.WriteLine(term); + ++term; + } + + term = 0; + do + { + Console.WriteLine(term); + ++term; + } while (term == 0); +} + +// Define other methods and classes here diff --git a/CSharp CheatSeet/4-4 For_ForEach.linq b/CSharp CheatSeet/4-4 For_ForEach.linq new file mode 100644 index 0000000..348d7b0 --- /dev/null +++ b/CSharp CheatSeet/4-4 For_ForEach.linq @@ -0,0 +1,37 @@ + + +void Main() +{ + var array = new[] {1,3,5}; + + Console.WriteLine("for文"); + var length = array.Length; + for (int i = 0; i < length; i++) + { + Console.WriteLine(array[i]); + } + + Console.WriteLine("foreach文:配列"); + foreach (var e in array) + { + Console.WriteLine(e); + } + + Console.WriteLine("foreach文:Enumerator"); + var enumerable = Enumerable.Range(1, 5); + foreach (var e in enumerable) + { + Console.WriteLine(e); + } + + Console.WriteLine("foreach文:cast"); + //int型とdouble型を混ぜた配列をobject[] 型として宣言 + var objects = new object[] { 1, 3, 4.5d }; + //要素型はvarだとobjectになるが、intで宣言するとキャストされるため、 + //要素がdoubleの時にキャストに失敗して実行時例外がスローされる + foreach (int e in objects) + { + Console.WriteLine(e); + } +} + diff --git a/CSharp CheatSeet/4-5 Break_Continue.linq b/CSharp CheatSeet/4-5 Break_Continue.linq new file mode 100644 index 0000000..c4d3d6b --- /dev/null +++ b/CSharp CheatSeet/4-5 Break_Continue.linq @@ -0,0 +1,18 @@ + + +void Main() +{ + var array = new [] {1,2,3,4,5}; + //奇数の時は次の繰り返しへ + //4のときにforeachを終了させるため + //出力されるのは2のみ + foreach (var e in array) + { + if (e % 2 == 1) + continue; + if (e == 4) + break; + Console.WriteLine(e); + } +} + diff --git a/CSharp CheatSeet/5-1 NameSpace.linq b/CSharp CheatSeet/5-1 NameSpace.linq new file mode 100644 index 0000000..da67467 --- /dev/null +++ b/CSharp CheatSeet/5-1 NameSpace.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + var a = new N1.A(); + var b = new N1.N2.B(); + var c = new N1.N2.C(); + a.Dump(); //for test + b.Dump(); + c.Dump(); +} + +} // コンテキストであるUserQeryクラスのスコープを閉じる(※LINQPad実行用) + +// ★以下にクラスメソッドなど自由に定義できる★ + +namespace N1 +{ + class A {} + + namespace N2 + { + class C {} + } +} + +namespace N1.N2 +{ + class B { } +} + +partial class UserQuery { // コンテキストのスコープを再び開く \ No newline at end of file diff --git a/CSharp CheatSeet/5-2 Using.linq b/CSharp CheatSeet/5-2 Using.linq new file mode 100644 index 0000000..961f52f --- /dev/null +++ b/CSharp CheatSeet/5-2 Using.linq @@ -0,0 +1,38 @@ + + System + System.Text + + +} // コンテキストであるUserQeryクラスのスコープを閉じる + +namespace CSharpCheatSheet +{ + using MyDateTime = N2.DateTime; + + class Program + { + static void Main(string[] args) + { + // usingによりSystem.Text.StringBuilderを参照 + var sb = new StringBuilder(); + // System.DateTimeを参照 + var now = DateTime.Now; + // namespace aliasによりCSharpCheatSheet.N2.MyDateTimeを参照 + var dateTime = new MyDateTime(); + // namespace aliasがない場合はこのように全ての参照箇所で完全修飾子が必要になる + var dateTime2 = new N2.DateTime(); + + sb.Dump(); // for test + now.Dump(); + dateTime.Dump(); + dateTime2.Dump(); + } + } +} + +namespace N2 +{ + public class DateTime { } +} + +partial class UserQuery { // コンテキストのスコープを再び開く \ No newline at end of file diff --git a/CSharp CheatSeet/6-1 Class.linq b/CSharp CheatSeet/6-1 Class.linq new file mode 100644 index 0000000..111b357 --- /dev/null +++ b/CSharp CheatSeet/6-1 Class.linq @@ -0,0 +1,33 @@ + + +void Main() +{ + new MyClass().Try(); +} + +public class MyClass +{ + public static readonly int DefaultLimit = 10; + + private int term; + + public MyClass() : this(DefaultLimit) + {} + + public MyClass(int limit) + { + Limit = limit; + } + + public int Limit { get; } + + public void Try() + { + term = 0; + while (term < Limit) + { + Console.WriteLine($"{term}回目"); + ++term; + } + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/6-2 StaticClass.linq b/CSharp CheatSeet/6-2 StaticClass.linq new file mode 100644 index 0000000..357fedf --- /dev/null +++ b/CSharp CheatSeet/6-2 StaticClass.linq @@ -0,0 +1,22 @@ + + +void Main() +{ + double mile = MileConverter.MileToKm(1); + mile.Dump(); +} + +public static class MileConverter +{ + public static readonly double MilePerKm = 0.62137; + + public static double KmToMile(double km) + { + return km * MilePerKm; + } + + public static double MileToKm(double mile) + { + return mile / MilePerKm; + } +} diff --git a/CSharp CheatSeet/6-3 Partial.linq b/CSharp CheatSeet/6-3 Partial.linq new file mode 100644 index 0000000..c444976 --- /dev/null +++ b/CSharp CheatSeet/6-3 Partial.linq @@ -0,0 +1,24 @@ + + +void Main() +{ + var my = new MyClass(); + my.Test(); + my.Test2(); +} + +public partial class MyClass +{ + public void Test() + { + Console.WriteLine("Test"); + } +} + +public partial class MyClass +{ + public void Test2() + { + Console.WriteLine("Test2"); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/6-4 TypeParameter.linq b/CSharp CheatSeet/6-4 TypeParameter.linq new file mode 100644 index 0000000..5ea4e3a --- /dev/null +++ b/CSharp CheatSeet/6-4 TypeParameter.linq @@ -0,0 +1,71 @@ + + +void Main() +{ + var c1 = new MyClass(); + c1.Value = "a"; + c1.Value.Dump(); + c1.DefaultValue().Dump(); + + var c2 = new MyClass(); + c2.Value = DateTime.Now; + c2.Value.Dump(); + c2.DefaultValue().Dump(); + + var c3 = new MyClass2(); + c3.DefaultValue().Dump(); + + var c4 = new MyClass3(); + c4.Execute(); + + var c5 = new MyClass4(); +} + +public class MyClass +{ + public T Value { get; set; } + + public T DefaultValue() + { + return default(T); + } +} + +public class MyClass2 where T : new () +{ + public T DefaultValue() + { + //new () 制約があるため、Tのデフォルトコンストラクタ呼び出しによるインスタンス化が可能 + return new T(); + } +} + +public class MyClass3 where T : IPrintable, new() +{ + public void Execute() + { + //TはIPrintableを実装している + new T().Print(); + } +} + +public interface IPrintable +{ + void Print(); +} + +public class Printable : IPrintable +{ + public void Print() + { + Console.WriteLine("Printable Prints"); + } +} + +//複数の型パラメーターがある場合は、それぞれに制約を指定することが可能 +public class MyClass4 + where K: class + where V: struct +{ + +} \ No newline at end of file diff --git a/CSharp CheatSeet/6-5 NestedType.linq b/CSharp CheatSeet/6-5 NestedType.linq new file mode 100644 index 0000000..b69c531 --- /dev/null +++ b/CSharp CheatSeet/6-5 NestedType.linq @@ -0,0 +1,43 @@ + + +void Main() +{ + //protected internal なOuter1.Inner3にはアクセスできるが、 + //privateなOuter1.Inner2にはアクセスできない + var inner = new Outer1.Inner3(); + inner.Execute(); + + var outer = new Outer1(); + outer.Execute(); +} + +public class Outer1 +{ + private static void Run() + { + Console.WriteLine("Run"); + } + + public void Execute() + { + //包含するクラスからなのでprivateなInner2にアクセスできる + var inner = new Inner2(); + inner.Execute(); + } + + public class Inner1 + { + public void Execute() + { + //入れ子になったクラスから包含する型のprivateメソッドにアクセスできる + Run(); + } + } + + private class Inner2 : Inner1 + {} + + protected internal class Inner3 : Inner1 + {} +} + diff --git a/CSharp CheatSeet/7-1 Method.linq b/CSharp CheatSeet/7-1 Method.linq new file mode 100644 index 0000000..45215ff --- /dev/null +++ b/CSharp CheatSeet/7-1 Method.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + var my = new MyClass(); + my.Run("text"); + MyClass.InternalRun(); +} + +public class MyClass +{ + + static internal void InternalRun() + { + Console.WriteLine("static internal Run"); + } + + public void Run(string text) + { + Console.WriteLine(text); + } + + protected void ProtectedRun() + { + Console.WriteLine("ProtectedRun"); + } + + private void PrivateRun() + { + Console.WriteLine("InternaRun"); + } +} diff --git a/CSharp CheatSeet/7-2 Ref_Out.linq b/CSharp CheatSeet/7-2 Ref_Out.linq new file mode 100644 index 0000000..6fd4bf6 --- /dev/null +++ b/CSharp CheatSeet/7-2 Ref_Out.linq @@ -0,0 +1,34 @@ + + +void Main() +{ + var i = 1; + var j = 2; + Swap(ref i, ref j); + //2 + i.Dump(); + //1 + j.Dump(); + + var k = 0; + int l; + //初期化済みの値、未初期化の値両方利用できる + Out(out k, out l); + //1 + k.Dump(); + //2 + l.Dump(); +} + +static void Swap(ref int x, ref int y) +{ + var temp = x; + x = y; + y = temp; +} + +static void Out(out int x, out int y) +{ + x = 1; + y = 2; +} diff --git a/CSharp CheatSeet/7-3 ParameterArray.linq b/CSharp CheatSeet/7-3 ParameterArray.linq new file mode 100644 index 0000000..885058b --- /dev/null +++ b/CSharp CheatSeet/7-3 ParameterArray.linq @@ -0,0 +1,17 @@ + + +void Main() +{ + var array = new[] {1,2,3}; + //3個の引数が指定されました + Param(array); + //2個の引数が指定されました + Param(1, 2); + //0個の引数が指定されました + Param(); +} + +static void Param(params int[] array) +{ + Console.WriteLine($"{array.Length}個の引数が指定されました"); +} \ No newline at end of file diff --git a/CSharp CheatSeet/7-4 DefaultArgument.linq b/CSharp CheatSeet/7-4 DefaultArgument.linq new file mode 100644 index 0000000..ab0f9e9 --- /dev/null +++ b/CSharp CheatSeet/7-4 DefaultArgument.linq @@ -0,0 +1,14 @@ + + +void Main() +{ + //x=1 y=a + Test(1); + //x=2 y=b + Test(2, "b"); +} + +static void Test(int x, string y = "a") +{ + Console.WriteLine($"x={x} y={y}"); +} \ No newline at end of file diff --git a/CSharp CheatSeet/7-5 ExtensionMethod.linq b/CSharp CheatSeet/7-5 ExtensionMethod.linq new file mode 100644 index 0000000..a5f0001 --- /dev/null +++ b/CSharp CheatSeet/7-5 ExtensionMethod.linq @@ -0,0 +1,17 @@ + + +void Main() +{ + var s = "abcd"; + var text = "CD"; + //true + s.ContainsIgnoreCase(text).Dump(); +} + +public static class MyExtensions +{ + public static bool ContainsIgnoreCase(this string s, string text) + { + return s.ToLower().Contains(text.ToLower()); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/8-1 Property.linq b/CSharp CheatSeet/8-1 Property.linq new file mode 100644 index 0000000..d3a46e7 --- /dev/null +++ b/CSharp CheatSeet/8-1 Property.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + var my = new MyClass(); + my.Value1 = 3; +} + +public class MyClass +{ + private int value1; + public int Value1 + { + get + { + return value1; + } + set + { + if (value != value1) + { + value1 = value; + ValueChanged(); + } + } + } + + private void ValueChanged() + { + Console.WriteLine("ValueChanged"); + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/8-2 AutoProperty.linq b/CSharp CheatSeet/8-2 AutoProperty.linq new file mode 100644 index 0000000..08882f8 --- /dev/null +++ b/CSharp CheatSeet/8-2 AutoProperty.linq @@ -0,0 +1,32 @@ + + +void Main() +{ + var my = new MyClass(); + my.Dump(); + my.UpdateValue1(); + my.Value2 = 12; + my.Dump(); +} + +public class MyClass +{ + public int Value1 { get; private set; } + + public int Value2 { get; set; } = 2; + + public int Value3 { get; } + + public MyClass() + { + //getter only プロパティはコンストラクタでも代入可能 + Value3 = 3; + } + + public void UpdateValue1() + { + //privateなsetterなのでインスタンス内から変更可能 + //Value3は更新できない + Value1 = 1; + } +} \ No newline at end of file diff --git a/CSharp CheatSeet/9-1 Event.linq b/CSharp CheatSeet/9-1 Event.linq new file mode 100644 index 0000000..f6a46ff --- /dev/null +++ b/CSharp CheatSeet/9-1 Event.linq @@ -0,0 +1,60 @@ + + +void Main() +{ + //EventHandlerのインスタンスを追加する、もしくは直接追加することが可能 + //意味合いとしては同じだが、別のインスタンスとして追加される + Changed += new EventHandler(OnChanged); + Changed += OnChanged; + //EventHandlerに一つも購読のハンドラが登録されていないとnullであるため、 + //null条件演算子経由でイベントを発火させている + Changed?.Invoke(this, new EventArgs()); + //イベントの購読を解除できる + Changed -= OnChanged; + Changed?.Invoke(this, new EventArgs()); + + ValueChanged += OnValueChanged; + ValueChanged.Invoke(this, new MyEventArgs(3)); +} + +void OnChanged(object sender, EventArgs ea) +{ + Console.WriteLine("OnChanged"); +} + +void OnValueChanged(object sender, MyEventArgs ea) +{ + Console.WriteLine($"OnValueChanged {ea.Value}"); +} + +event EventHandler Changed; +event EventHandler ValueChanged; + +class MyEventArgs : EventArgs +{ + public int Value { get; } + public MyEventArgs(int value) + { + Value = value; + } +} + +//event構文はaddとremove処理を明示的に記述できる +//省略した場合のコードは意味合い的には下記のコードと同様だが、 +//実際にはスレッドセーフなコードが生成されている +private EventHandler customHandler; +event EventHandler CustomHandler +{ + add + { + customHandler += value; + } + remove + { + customHandler -= value; + } +} + +//自前で定義したdelegateをイベントの型として利用することもできる +public delegate void MyEventHandler(); +public event MyEventHandler MyChanged; \ No newline at end of file