Exemple #1
0
        private void F2()
        {
            Foo foo = null;

            try
            {
                foo    = (Foo)RuntimeHelpers.GetUninitializedObject(typeof(Foo));
                foo.F1 = 2;
                foo.F2 = 2;
                var constructorInfo = typeof(Foo).GetConstructor(new Type[0]);
                constructorInfo !.Invoke(foo, null);

                foo.F1 = 5;
                foo.F2 = 5;
                constructorInfo !.Invoke(foo, null);
            }
            catch
            {
                // 忽略
            }
            finally
            {
                try
                {
                    foo?.Dispose();
                }
                catch
                {
                    // 可以调用到 Dispose 方法
                }
            }
        }
Exemple #2
0
        public static void GetUninitializedObject_Nullable()
        {
            // Nullable returns the underlying type instead
            object o = RuntimeHelpers.GetUninitializedObject(typeof(int?));

            Assert.Equal(0, Assert.IsType <int>(o));
        }
        public void ShootAtOpponent_RetrievesTheGameFromTheRepositoryAndUsesItToShoot()
        {
            //Arrange
            Guid           userId           = Guid.NewGuid();
            Guid           gameId           = Guid.NewGuid();
            GridCoordinate targetCoordinate = new GridCoordinate(1, 1);

            var   existingGameMock = new Mock <IGame>();
            IGame existingGame     = existingGameMock.Object;

            _gameRepositoryMock.Setup(repo => repo.GetById(It.IsAny <Guid>())).Returns(existingGame);

            ShotResult expectedShotResult = RuntimeHelpers.GetUninitializedObject(typeof(ShotResult)) as ShotResult;

            existingGameMock.Setup(game => game.ShootAtOpponent(It.IsAny <Guid>(), It.IsAny <GridCoordinate>())).Returns(expectedShotResult);

            //Act
            var returnedShotResult = _service.ShootAtOpponent(gameId, userId, targetCoordinate);

            //Assert
            Assert.That(returnedShotResult, Is.SameAs(expectedShotResult),
                        "The ShotResult returned should be an instance created by the ShootAtOpponent method of the Game.");

            _gameRepositoryMock.Verify(repo => repo.GetById(gameId), Times.Once,
                                       "The 'GetById' method of the IGameRepository is not called correctly.");

            existingGameMock.Verify(game => game.ShootAtOpponent(userId, targetCoordinate), Times.Once,
                                    "The 'ShootAtOpponent' method of the game returned by the IGameRepository is not called correctly. " +
                                    "The id of the shooter and the target coordinate should be provided.");
        }
Exemple #4
0
 public static object?Raw(Type?type)
 {
     if (type is null)
     {
         return(null);
     }
     return(RuntimeHelpers.GetUninitializedObject(type));
 }
Exemple #5
0
        public static void GetUninitalizedObject_DoesNotRunBeforeFieldInitCctors()
        {
            object o = RuntimeHelpers.GetUninitializedObject(typeof(ClassWithBeforeFieldInitCctor));

            Assert.IsType <ClassWithBeforeFieldInitCctor>(o);

            Assert.Null(AppDomain.CurrentDomain.GetData("ClassWithBeforeFieldInitCctor_CctorRan"));
        }
Exemple #6
0
        public static void GetUninitalizedObject_RunsNormalStaticCtors()
        {
            object o = RuntimeHelpers.GetUninitializedObject(typeof(ClassWithNormalCctor));

            Assert.IsType <ClassWithNormalCctor>(o);

            Assert.Equal(true, AppDomain.CurrentDomain.GetData("ClassWithNormalCctor_CctorRan"));
        }
Exemple #7
0
        public static void GetUninitializedObject_InvalidArguments_ThrowsException()
        {
            Assert.Throws <ArgumentNullException>("type", () => RuntimeHelpers.GetUninitializedObject(null));

            Assert.Throws <ArgumentException>(() => RuntimeHelpers.GetUninitializedObject(typeof(string)));                                 // special type
            Assert.Throws <MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.IO.Stream)));                   // abstract type
            Assert.Throws <MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.Collections.IEnumerable)));     // interface
            Assert.Throws <MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.Collections.Generic.List <>))); // generic definition
        }
Exemple #8
0
 public override int Run(InterpretedFrame frame)
 {
     if (frame.Peek() == null)
     {
         frame.Pop();
         frame.Push(RuntimeHelpers.GetUninitializedObject(_defaultValueType));
     }
     return(1);
 }
Exemple #9
0
                        static object NullableGetValueOrDefault(object thisObject, object[] args,
                                                                Type thisType)
                        {
                            if (thisObject == null)
                            {
                                return(RuntimeHelpers.GetUninitializedObject(thisType));
                            }

                            return(thisObject);
                        }
Exemple #10
0
        static void Main(string[] args)
        {
            var calculator = RuntimeHelpers.GetUninitializedObject(typeof(TaxCalculation)) as TaxCalculation;

            Console.WriteLine(calculator.CalculateVat(11.99));

            var dog = RuntimeHelpers.GetUninitializedObject(typeof(Dog)) as Dog;

            Console.WriteLine(dog.Bark());
        }
        internal static IntPtr CreateNSObject(IntPtr type_gchandle, IntPtr handle, Flags flags)
        {
            // This function is called from native code before any constructors have executed.
            var type = (Type)Runtime.GetGCHandleTarget(type_gchandle);
            var obj  = (NSObject)RuntimeHelpers.GetUninitializedObject(type);

            obj.handle = handle;
            obj.flags  = flags;
            return(Runtime.AllocGCHandle(obj));
        }
Exemple #12
0
        public void SupportsInitializerStyleClassConstructors()
        {
            var ctor        = typeof(ClassWithConstructor).GetConstructors().First();
            var initter     = Shim.Create <Action <ClassWithConstructor> >(ctor, ConstructorDelegateKind.Initializer);
            var rawInstance = (ClassWithConstructor)RuntimeHelpers.GetUninitializedObject(typeof(ClassWithConstructor));

            initter(rawInstance);

            Assert.True(rawInstance.HasBeenConstructedProperly);
        }
Exemple #13
0
        public T GetExamples()
        {
            T   instance = (T)RuntimeHelpers.GetUninitializedObject(typeof(T));
            var generateExampleAttribute = typeof(T).GetCustomAttribute <GenerateExampleAttribute>();

            if (generateExampleAttribute?.Values.Length > 0)
            {
                if (generateExampleAttribute.Properties.Length == 0)
                {
                    return((T)Activator.CreateInstance
                           (
                               typeof(T),
                               generateExampleAttribute.Values.ToArray()
                           ));
                }
                else if (generateExampleAttribute.Properties.Length != generateExampleAttribute.Values.Length)
                {
                    Func <object, object, string> aggregator = (x, y) =>
                    {
                        y = y is string?$"\"{y}\"" : y;
                        return((x == null) ? y.ToString() : string.Join(", ", x, y));
                    };
                    throw new ArgumentException
                          (
                              $"The number of properties and values supplied to " +
                              $"{nameof(GenerateExampleAttribute)} do not match. " +
                              $"Properties (Length: {generateExampleAttribute.Properties.Length}) = " +
                              $"{{ {generateExampleAttribute.Properties.Aggregate(null, aggregator)} }}; " +
                              $"Values (Length: {generateExampleAttribute.Values.Length}) = " +
                              $"{{ {generateExampleAttribute.Values.Aggregate(null, aggregator)} }}."
                          );
                }
                else
                {
                    var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
                    foreach
                    (
                        var(propName, index)
                        in generateExampleAttribute
                        .Properties
                        .Select((item, index) => (item, index))
                    )
                    {
                        props
                        .First(x => x.Name == propName)?
                        .SetValue
                        (
                            instance,
                            generateExampleAttribute.Values[index]
                        );
                    }
                }
            }
            return(instance);
        }
                        static object NullableGetValueOrDefault(object thisObject, object[] args,
                                                                [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
                                                                Type thisType)
                        {
                            if (thisObject == null)
                            {
                                return(RuntimeHelpers.GetUninitializedObject(thisType));
                            }

                            return(thisObject);
                        }
Exemple #15
0
        public override void WriteData(PropertyValue value)
        {
            object?refVal   = value.ReferenceValue;
            bool   hasValue = refVal is not null;

            TraceLoggingDataCollector.AddScalar(hasValue);
            PropertyValue val = valueInfo.PropertyValueFactory(hasValue
                ? refVal
                : RuntimeHelpers.GetUninitializedObject(valueInfo.DataType));

            this.valueInfo.WriteData(val);
        }
Exemple #16
0
        public static object GetUninitializedObject(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
#if netcoreapp11
            return(RuntimeHelpers.GetUninitializedObject(type));
#else
            return(s_getUninitializedObjectDelegate(type));
#endif // netcoreapp11
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var calculator = new TaxCalculator("valid_license");

            Console.WriteLine(calculator.CalculateVAT(11.99));

            var calculator2 = RuntimeHelpers.GetUninitializedObject(typeof(TaxCalculator)) as TaxCalculator;

            Console.WriteLine(calculator2.CalculateVAT(11.99));

            var dog = RuntimeHelpers.GetUninitializedObject(typeof(Dog)) as Dog;

            Console.WriteLine(dog.Bark());
        }
Exemple #18
0
        internal static IntPtr CreateNSObject(IntPtr type_gchandle, IntPtr handle, Flags flags)
        {
            // This function is called from native code before any constructors have executed.
            var type = (Type)Runtime.GetGCHandleTarget(type_gchandle);

            try {
                var obj = (NSObject)RuntimeHelpers.GetUninitializedObject(type);
                obj.handle = handle;
                obj.flags  = flags;
                return(Runtime.AllocGCHandle(obj));
            } catch (Exception e) {
                throw ErrorHelper.CreateError(8041, e, Errors.MX8041 /* Unable to create an instance of the type {0} */, type.FullName);
            }
        }
Exemple #19
0
 public static void GetUninitializedObject_Nullable()
 {
     // Nullable returns the underlying type instead
     Assert.Equal(typeof(int), RuntimeHelpers.GetUninitializedObject(typeof(Nullable <int>)).GetType());
 }
Exemple #20
0
 public static void GetUninitializedObject_DoesNotRunConstructor()
 {
     Assert.Equal(42, new ObjectWithDefaultCtor().Value);
     Assert.Equal(0, ((ObjectWithDefaultCtor)RuntimeHelpers.GetUninitializedObject(typeof(ObjectWithDefaultCtor))).Value);
 }
Exemple #21
0
        public static void GetUninitializedObject_Struct()
        {
            object o = RuntimeHelpers.GetUninitializedObject(typeof(Guid));

            Assert.Equal(Guid.Empty, Assert.IsType <Guid>(o));
        }
Exemple #22
0
 public static void GetUninitializedObject_InvalidArguments_ThrowsException(Type typeToInstantiate, Type expectedExceptionType)
 {
     Assert.Throws(expectedExceptionType, () => RuntimeHelpers.GetUninitializedObject(typeToInstantiate));
 }
 public object RH_GetUninitializedObject()
 {
     return(RuntimeHelpers.GetUninitializedObject(_objType));
 }
Exemple #24
0
 private object GetUninitializedObject(Type objType)
 {
     return(RuntimeHelpers.GetUninitializedObject(objType));
 }
Exemple #25
0
 private static object?CreateValueType(Type t) => RuntimeHelpers.GetUninitializedObject(t);
Exemple #26
0
        public void GenerateLoad(IILGen ilGenerator, Action <IILGen> pushReader, Action <IILGen> pushCtx,
                                 Action <IILGen> pushDescriptor, Type targetType)
        {
            if (targetType == typeof(object))
            {
                var resultLoc  = ilGenerator.DeclareLocal(typeof(DynamicObject), "result");
                var labelNoCtx = ilGenerator.DefineLabel();
                ilGenerator
                .Do(pushDescriptor)
                .Castclass(typeof(ObjectTypeDescriptor))
                .Newobj(typeof(DynamicObject).GetConstructor(new[] { typeof(ObjectTypeDescriptor) }) !)
                .Stloc(resultLoc)
                .Do(pushCtx)
                .BrfalseS(labelNoCtx)
                .Do(pushCtx)
                .Ldloc(resultLoc)
                .Callvirt(() => default(ITypeBinaryDeserializerContext).AddBackRef(null))
                .Mark(labelNoCtx);
                var idx = 0;
                foreach (var pair in _fields)
                {
                    var idxForCapture = idx;
                    ilGenerator.Ldloc(resultLoc);
                    ilGenerator.LdcI4(idx);
                    pair.Value.GenerateLoadEx(ilGenerator, pushReader, pushCtx,
                                              il =>
                                              il.Do(pushDescriptor)
                                              .LdcI4(idxForCapture)
                                              .Callvirt(() => default(ITypeDescriptor).NestedType(0)), typeof(object),
                                              _typeSerializers.ConvertorGenerator);
                    ilGenerator.Callvirt(() => default(DynamicObject).SetFieldByIdxFast(0, null));
                    idx++;
                }

                ilGenerator
                .Ldloc(resultLoc)
                .Castclass(typeof(object));
            }
            else
            {
                var resultLoc          = ilGenerator.DeclareLocal(targetType, "result");
                var labelNoCtx         = ilGenerator.DefineLabel();
                var defaultConstructor = targetType.GetConstructor(Type.EmptyTypes);
                if (defaultConstructor == null)
                {
                    ilGenerator
                    .Ldtoken(targetType)
                    .Call(() => Type.GetTypeFromHandle(new RuntimeTypeHandle()))
                    .Call(() => RuntimeHelpers.GetUninitializedObject(null))
                    .Castclass(targetType);
                }
                else
                {
                    ilGenerator
                    .Newobj(defaultConstructor);
                }

                ilGenerator
                .Stloc(resultLoc)
                .Do(pushCtx)
                .BrfalseS(labelNoCtx)
                .Do(pushCtx)
                .Ldloc(resultLoc)
                .Callvirt(() => default(ITypeBinaryDeserializerContext).AddBackRef(null))
                .Mark(labelNoCtx);
                var props = targetType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                for (var idx = 0; idx < _fields.Count; idx++)
                {
                    var idxForCapture = idx;
                    var pair          = _fields[idx];
                    var prop          = props.FirstOrDefault(p => GetPersistentName(p) == pair.Key);
                    if (prop == null || !_typeSerializers.IsSafeToLoad(prop.PropertyType))
                    {
                        pair.Value.GenerateSkipEx(ilGenerator, pushReader, pushCtx);
                        continue;
                    }

                    ilGenerator.Ldloc(resultLoc);
                    pair.Value.GenerateLoadEx(ilGenerator, pushReader, pushCtx,
                                              il => il.Do(pushDescriptor).LdcI4(idxForCapture)
                                              .Callvirt(() => default(ITypeDescriptor).NestedType(0)),
                                              prop.PropertyType, _typeSerializers.ConvertorGenerator);
                    ilGenerator.Callvirt(prop.GetAnySetMethod() !);
                }

                ilGenerator.Ldloc(resultLoc);
            }
        }
Exemple #27
0
 private object GetUninitializedObject(
     [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
     Type objType)
 {
     return(RuntimeHelpers.GetUninitializedObject(objType));
 }
Exemple #28
0
 public static T Raw <T>()
 {
     return((T)RuntimeHelpers.GetUninitializedObject(typeof(T)) !);
 }
Exemple #29
0
 static Dog CreateWeirdDog()
 {
     return((Dog)RuntimeHelpers.GetUninitializedObject(typeof(Dog)));
 }
Exemple #30
0
 public static object GetSafeUninitializedObject(Type type) => RuntimeHelpers.GetUninitializedObject(type);