mardi 30 août 2016

Can a ConstructorInfo have no DeclaringType

I was browsing the System.Linq.Expressions source code on GitHub and found the following code

public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments)
{
    ContractUtils.RequiresNotNull(constructor, nameof(constructor));
    ContractUtils.RequiresNotNull(constructor.DeclaringType, nameof(constructor));

    // ...
}

I was confused by the second null check, so went to MSDN. It had the following to say about ConstructorInfo.DeclaringType:

The DeclaringType property retrieves a reference to the Type object for the type that declares this member. A member of a type is either declared by the type or inherited from a base type, so the Type object returned by the DeclaringType property might not be the same as the Type object used to obtain the current MemberInfo object.

If the Type object from which this MemberInfo object was obtained did not declare this member, the DeclaringType property will represent one of its base types.

If the MemberInfo object is a global member (that is, if it was obtained from the Module.GetMethods method, which returns global methods on a module), the returned DeclaringType will be null.

So it seems that DeclaringType can be null for a MemberInfo (the class from which ConstructorInfo derives). But I am uncertain whether it can be null or not for ConstructorInfo.

So to my questions:

  1. Can ConstructorInfo.DeclaringType ever be null? Why is the System.Linq.Expressions code checking for it?

  2. If DeclaringType can be null, can you provide an example?

  3. If DeclaringType can be null, does this imply that the CLR supports global constructors? (I've tried researching this but can't find anything)





Aucun commentaire:

Enregistrer un commentaire