In class and method definitions, it's possible to add type constraints like where T : IFoo
.
Is it possible to reflect over those constraints with System.Type
or MethodInfo
? I haven't found anything so far; any help will be appreciated.
You can iterate through the generic parameters to the type, and for each parameter, you can ask for the constraint types.
You do this using:
Type<T>
, you would find T
.Take a look at this code, which you can run through LINQPad:
void Main()
{
Type type = typeof(TestClass<>);
foreach (var parm in type.GetGenericArguments())
{
Debug.WriteLine(parm.Name);
parm.GetGenericParameterConstraints().Dump();
}
}
public class TestClass<T>
where T : Stream
{
}
The output is:
T Type [] (1 item) typeof (Stream)
To find other constraints, such as new()
, you can use the .GenericParameterAttributes
flags enum, example:
void Main()
{
Type type = typeof(TestClass<>);
foreach (var parm in type.GetGenericArguments())
{
Debug.WriteLine(parm.Name);
parm.GetGenericParameterConstraints().Dump();
parm.GenericParameterAttributes.Dump();
}
}
public class TestClass<T>
where T : new()
{
}
Which outputs:
T Type [] (1 item) typeof (Stream) DefaultConstructorConstraint
You can use the GetGenericParameterConstraints() method to do that.
Using a previously found System.Type
you can use GetGenericParameterConstraints()
.
Here's an excellent MSDN article on Generics and Reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With