Last active
January 28, 2017 04:00
-
-
Save kazyx/9cdc033dd3bf19724b5253c759705a8f to your computer and use it in GitHub Desktop.
How to detect Type of generic property, in other words generic argument, from derived class
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
public class Main { | |
public Type GetTypeOfGenericArg(Type derivedClassType) { | |
var typedMyInterfaceType = derivedClassType.GetInterface(typeof(MyInterface<>).FullName); | |
// If derivedClassType is 'MyFoo', typedMyInterfaceType is typeof(MyInterface<Foo>) | |
return typedMyInterfaceType.GetGenericArguments()[0]; | |
} | |
public Type GetTypeOfGenericArgByPropertyName(Type derivedClassType) { | |
var myParamPropertyInfo = derivedClassType.GetProperty(nameof(MyInterface.MyParameter)); | |
// If derivedClassType is 'MyFoo', myParamPropertyInfo is PropertyInfo of MyFoo.MyParameter | |
return myParamPropertyInfo.PropertyType; | |
} | |
} |
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
public interface MyInterface<T> { | |
T MyParameter { set; get; } | |
} | |
public class Foo { | |
public string Bar { set; get; } | |
} | |
public class MyFoo : MyInterface<Foo> { | |
public Foo MyParameter { set; get; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment