Created
March 2, 2020 11:15
-
-
Save kostapc/155ee31638607c589763111382e68598 to your computer and use it in GitHub Desktop.
Testing c# generics
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.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace SomeGenerics { | |
| class Program { | |
| static void Main(string[] args) | |
| { | |
| var n = new Some<Parent>(); | |
| Type good = typeof(Some<Parent>); | |
| Type bad = typeof(Some<Child>); | |
| Console.WriteLine("good: " + n.checkMe(good)); | |
| Console.WriteLine("bad: " + n.checkMe(bad)); | |
| foreach(Type genType in good.GenericTypeArguments) | |
| { | |
| Console.WriteLine($"generic type: {genType}"); | |
| } | |
| Type genericType = bad.GenericTypeArguments[0]; | |
| Parent ObjectFromGeneric = Activator.CreateInstance(genericType) as Parent; // as возвращает null если не может привести | |
| Console.WriteLine("from generic (new): " + ObjectFromGeneric?.Me()); // поэтому тут вызов с проверкой на null - ?. | |
| Console.WriteLine("from generic (override): " + ObjectFromGeneric?.RealMe()); | |
| Console.WriteLine("{END}"); | |
| Console.ReadKey(); | |
| } | |
| class Parent { | |
| public string Me() | |
| { | |
| return "parent"; | |
| } | |
| public virtual string RealMe() | |
| { | |
| return "parent"; | |
| } | |
| } | |
| class Child : Parent { | |
| public new string Me() | |
| { | |
| return "child"; | |
| } | |
| public override string RealMe() { | |
| return "child"; | |
| } | |
| } | |
| class Some<T> where T : Parent { | |
| internal bool checkMe(Type asdf) | |
| { | |
| return asdf == this.GetType(); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment