Method may only be called on a Type for which Type.IsGenericParameter is true

后端 未结 5 1294
一整个雨季
一整个雨季 2020-12-30 01:30

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(         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-30 02:11

    How do I avoid this error without a try/catch?

    You almost certainly can't. When you call p.GetValue, you're calling the getter on that property, which could throw any kind of exception. For example, SqlConnection.ServerVersion will throw an exception if the connection is closed, and you have to handle that.

    Where are these extra members coming from?

    Your obj already contains the RuntimeType object representing SqlConnection, rather than an instance of SqlConnection. obj.GetMembers() would return the 65 members of the SqlConnection class, but by calling GetType() again, you get the 188 members of RuntimeType.

    What is IsGenericParameter?

    Instead of representing a class, you can have an instance of RuntimeType that represents a generic parameter to a class or method (The T and TOutput in List.ConvertAll. In this case, DeclaringMethod on the object representing TOutput would let you get a MethodInfo object representing the ConvertAll<> method. However, when the RuntimeType represents a class, the idea of a declaring method makes no sense. That's why reading the property causes the exception that you saw.

提交回复
热议问题