Created
October 25, 2025 12:05
-
-
Save sunmeat/970fd332da9331d6f0b9ff6cb2423ba4 to your computer and use it in GitHub Desktop.
generic interface C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Text; | |
| namespace GenericInterfaceExample | |
| { | |
| public interface IPrintable<T> where T : struct | |
| { | |
| void Print(); | |
| } | |
| class MyCollection<T> : IPrintable<T> where T : struct | |
| { | |
| T[] arr; | |
| public MyCollection(T[] arr) | |
| { | |
| if (arr == null || arr.Length == 0) throw new Exception("Помилка!"); | |
| this.arr = new T[arr.Length]; | |
| Array.Copy(arr, this.arr, arr.Length); | |
| // array.copy використовується для копіювання значень структурних типів | |
| } | |
| public void Print() | |
| { | |
| Console.WriteLine("Тип: {0}", typeof(T)); | |
| Console.WriteLine("Масив: "); | |
| foreach (T item in arr) | |
| Console.Write("{0}\t", item); | |
| Console.WriteLine("\n"); | |
| } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Console.OutputEncoding = Encoding.UTF8; | |
| byte[] byte_arr = new byte[5] { 4, 5, 18, 56, 8 }; | |
| var mc1 = new MyCollection<byte>(byte_arr); | |
| mc1.Print(); | |
| float[] float_arr = new float[8] { 12.0f, 1f, 3.4f, 2.8f, -334.7f, -2f, 7.89f, 0 }; | |
| var mc2 = new MyCollection<float>(float_arr); | |
| mc2.Print(); | |
| Console.ReadLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment