1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 using System
.Reflection
;
6 using System
.Runtime
.CompilerServices
;
10 [CLSCompliantAttribute (false)]
11 public ref struct TypedReference
13 #region sync with object-internals.h
14 RuntimeTypeHandle type
;
19 [CLSCompliant (false)]
20 public static TypedReference
MakeTypedReference (object target
, FieldInfo
[] flds
)
23 throw new ArgumentNullException (nameof (target
));
25 throw new ArgumentNullException (nameof (flds
));
27 throw new ArgumentException (SR
.Arg_ArrayZeroError
, nameof (flds
));
29 var fields
= new IntPtr
[flds
.Length
];
30 var targetType
= (RuntimeType
)target
.GetType ();
31 for (int i
= 0; i
< flds
.Length
; i
++) {
32 var field
= flds
[i
] as RuntimeFieldInfo
;
34 throw new ArgumentException (SR
.Argument_MustBeRuntimeFieldInfo
);
36 throw new ArgumentException (SR
.Argument_TypedReferenceInvalidField
);
38 if (targetType
!= field
.GetDeclaringTypeInternal () && !targetType
.IsSubclassOf (field
.GetDeclaringTypeInternal ()))
39 throw new MissingMemberException (SR
.MissingMemberTypeRef
);
41 var fieldType
= (RuntimeType
)field
.FieldType
;
42 if (fieldType
.IsPrimitive
)
43 throw new ArgumentException (SR
.Arg_TypeRefPrimitve
);
44 if (i
< (flds
.Length
- 1) && !fieldType
.IsValueType
)
45 throw new MissingMemberException (SR
.MissingMemberNestErr
);
47 fields
[i
] = field
.FieldHandle
.Value
;
48 targetType
= fieldType
;
51 var result
= new TypedReference ();
54 InternalMakeTypedReference (&result
, target
, fields
, targetType
);
59 [MethodImplAttribute (MethodImplOptions
.InternalCall
)]
60 unsafe static extern void InternalMakeTypedReference (void* result
, Object target
, IntPtr
[] flds
, RuntimeType lastFieldType
);
62 public override int GetHashCode ()
64 if (Type
== IntPtr
.Zero
)
67 return __reftype (this).GetHashCode ();
70 public override bool Equals (object? o
)
72 throw new NotSupportedException (SR
.NotSupported_NYI
);
75 [CLSCompliant (false)]
76 public unsafe static object ToObject (TypedReference
value)
78 return InternalToObject (&value);
81 [MethodImplAttribute (MethodImplOptions
.InternalCall
)]
82 unsafe extern static object InternalToObject (void * value);
84 internal bool IsNull
{
86 return Value
== IntPtr
.Zero
&& Type
== IntPtr
.Zero
;
90 [CLSCompliant (false)]
91 public static Type
GetTargetType (TypedReference
value)
93 return __reftype (value);
96 [CLSCompliant (false)]
97 public static RuntimeTypeHandle
TargetTypeToken (TypedReference
value)
99 return __reftype (value).TypeHandle
;
102 [CLSCompliant (false)]
103 public unsafe static void SetTypedReference (TypedReference target
, Object
value)
105 throw new NotSupportedException ();