方法只能在Type堪称为这Type.IsGenericParameter是真实的 [英] Method may only be called on a Type for which Type.IsGenericParameter is true
问题描述
我得到的,它使用反射抛售一些对象属性,像下面的代码例行此错误。
I am getting this error on a routine which uses reflection to dump some object properties, something like the code below.
MemberInfo[] members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance) ;
foreach (MemberInfo m in members)
{
PropertyInfo p = m as PropertyInfo;
if (p != null)
{
object po = p.GetValue(obj, null);
...
}
}
实际的错误是异常被抛出由调用的目标
与内部异常方法只能叫上键入这Type.IsGenericParameter是真实的。
The actual error is "Exception has been thrown by the target of an invocation" with an inner exception of "Method may only be called on a Type for which Type.IsGenericParameter is true."
在这个阶段在调试器的obj显示为
At this stage in the debugger obj appears as
{Name = "SqlConnection" FullName = "System.Data.SqlClient.SqlConnection"}
与该类型System.RuntimeType
with the type System.RuntimeType
该方法m是{System.Reflection.MethodBase DeclaringMethod}
The method m is {System.Reflection.MethodBase DeclaringMethod}
注意obj是类型System.RuntimeType和成员包含188项而一个简单的
typeof运算(System.Data.SqlClient.SqlConnection).GetMembers。(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)只返回65
Note that obj is of type System.RuntimeType and members contains 188 items whereas a simple typeof(System.Data.SqlClient.SqlConnection).GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) only returns 65.
我试过两个OBJ和p.PropertyType检查isGenericParameter,但是这似乎是大多数属性虚假包括那些p.GetValue的作品。
I tried checking isGenericParameter on both obj and p.PropertyType, but this seems to be false for most properties including those where p.GetValue works.
所以,到底什么是键入该Type.IsGenericParameter是真的,更重要的
我怎么避免这个错误没有一个try / catch?
So what exactly is a "Type for which Type.IsGenericParameter is true" and more importantly how do I avoid this error without a try/catch?
推荐答案
首先,你在不正确的假设做了,那就是,你认为成员
返回一个实例成员<$的C $ C> System.Data.SqlClient.SqlConnection ,它没有。什么已恢复为的System.Type
的一个实例的成员。
Firstly, you've made in incorrect assumption, that is, you've assumed that members
has returned the members of an instance of System.Data.SqlClient.SqlConnection
, which it has not. What has been returned are the members of an instance of System.Type
.
从MSDN文档<一个HREF =http://msdn.microsoft.com/en-us/library/system.type.declaringmethod.aspx> DeclaringType :
获取 DeclaringMethod
属性
上的类型,其 IsGenericParameter
属性是假抛出一个
出现InvalidOperationException
。
所以...这是可以理解的,一个出现InvalidOperationException
被抛出,因为自然的,你不处理一个开放式泛型类型在这里。见的马克Gravells回答开放泛型类型的说明。
So... it's understandable that an InvalidOperationException
is being thrown, since naturally, you're not dealing with an open generic type here. See Marc Gravells answer for an explanation of open generic types.
这篇关于方法只能在Type堪称为这Type.IsGenericParameter是真实的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!