Pau*_*rth 11 .net generics reflection
我正在尝试检测Type对象的特定实例是否是通用的"IEnumerable"...
我能想到的最好的是:
// theType might be typeof(IEnumerable<string>) for example... or it might not
bool isGenericEnumerable = theType.GetGenericTypeDefinition() == typeof(IEnumerable<object>).GetGenericTypeDefinition()
if(isGenericEnumerable)
{
Type enumType = theType.GetGenericArguments()[0];
etc. ...// enumType is now typeof(string)
Run Code Online (Sandbox Code Playgroud)
但这似乎有点间接 - 是否有更直接/更优雅的方式来做到这一点?
Ken*_* K. 22
您可以使用
if(theType.IsGenericType && theType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type underlyingType = theType.GetGenericArguments()[0];
//do something here
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加了IsGenericType检查,感谢有用的评论
| 归档时间: |
|
| 查看次数: |
3991 次 |
| 最近记录: |