Created
June 10, 2019 17:29
-
-
Save mrnkr/55171a10a31456f6b074105aa33dc111 to your computer and use it in GitHub Desktop.
A simple example of reflection. Getting the first class that implements a given interface and calling one of its methods.
This file contains 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.IO; | |
using System.Linq; | |
using System.Reflection; | |
using FindMe; | |
namespace TestProj | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Assembly assem2 = Assembly.Load("FindMe"); | |
Type[] types = assem2.GetTypes(); | |
Type targetIface = typeof(IOperator); | |
var implQuery = | |
from type in types | |
where (targetIface.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface) | |
select type; | |
Type myType = implQuery.FirstOrDefault(); | |
IOperator instance = (IOperator)Activator.CreateInstance(myType); | |
instance.Operate(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment