简体   繁体   中英

How are types compared in .NET? How does the CLR identify they are the same or different?

How does the Type.Equals(Type) compare types to know if they are the same or not?

The original question was being confused because of what I had here in the body as what I thought would direct the question. Forget that part. The question is in the title.

EDIT: Lasse V. Larksen posed my question best:

"What makes up the identity of a .NET type"..."If I declare the exact same type, down to the namespace, in two different projects/assemblies, .NET consider them different, why?"

It's implemented like this: (from the reference source)

public virtual bool Equals(Type o)
{ 
    if ((object)o == null) 
        return false;

    return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));
}
public override bool Equals(object o)
{
    return (((o != null) && (o is Type)) && (this.UnderlyingSystemType == ((Type) o).UnderlyingSystemType));
}

This is from the latest reflected source.

ECMA-335 Common Language Infrastructure Partitions I and II dictate that each type will be known by a given type signature . It states how IL represents this signature and how the Virtual Execution System should interpret the signature, but it leaves how a conformant runtime implementation must actually implement this type signature up to the implementation (as far as I can tell).

New types—value types and reference types—are introduced into the CTS via type declarations expressed in metadata. In addition, metadata is a structured way to represent all information that the CLI uses to locate and load classes, lay out instances in memory, resolve method invocations, translate CIL to native code, enforce security, and set up runtime context boundaries.

However, to your question, regardless of how UnderlyingSystemType is actually implemented it will correlate to a unique reference using the containing:

  • Assembly
  • Module
  • Namespace
  • Parent Types (if any)
  • The Type itself

Partition II has the physical metadata for a TypeDef (section 22.37) which encodes this information.

Partition III contains the IL which represents loading a metadata token, known as a RuntimeHandle onto the stack. There are different handles for types, methods, and fields depending on the token given to the IL instructions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM