Last active
August 29, 2015 14:00
-
-
Save johnbfair/11263203 to your computer and use it in GitHub Desktop.
C# vs F# reflection over generic types
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
| // Intended to be executed in LINQPad | |
| //using System.Reflection | |
| void Main() | |
| { | |
| TypeImplementsInterfaceFilter(typeof(MySample2), typeof(MySample1<MySample2>)).Dump(); | |
| } | |
| public interface ISample<T> { } | |
| public class MySample1<T> : ISample<T> | |
| { | |
| public MySample1() {} | |
| } | |
| public class MySample2 | |
| { | |
| public MySample2() {} | |
| } | |
| // Define other methods and classes here | |
| public bool TypeImplementsInterfaceFilter(Type messageType, Type handlerType) | |
| { | |
| var interfaceType = handlerType.GetInterfaces() | |
| .FirstOrDefault(contract => contract.IsGenericType && | |
| typeof(ISample<>).Name == contract.GetGenericTypeDefinition().Name); | |
| if (interfaceType == null) { return false; } | |
| interfaceType.GetGenericArguments().First().Name.Dump(); | |
| messageType.Name.Dump(); | |
| return interfaceType.GetGenericArguments().First().Name == messageType.Name; | |
| } |
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
| // Intended to be executed where ever you want, but LINQPad is where it was written | |
| //open System.Reflection | |
| type ISample<'T> = | |
| abstract member MySample<'T> : unit -> unit | |
| type MySample1<'T>() = | |
| interface ISample<'T> with | |
| member x.MySample<'T>() = () | |
| type MySample2() = | |
| member x.MySample() = () | |
| let typeImplements (messageType:Type) (handlerType:Type) = | |
| let interfaces = | |
| handlerType.GetInterfaces() | |
| |> Array.filter (fun x -> x.IsGenericType && (typedefof<ISample<_>>).Name = x.GetGenericTypeDefinition().Name) | |
| interfaces.[0].GetGenericArguments().[0].Name |> Dump | |
| messageType.Name |> Dump | |
| interfaces.[0].GetGenericArguments().[0].Name = messageType.Name | |
| typeImplements typeof<MySample2> typeof<MySample1<MySample2>> |> Dump | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment