Reflector

Namespace: Gallio
We found 10 examples in language CSharp for this search. You will see 45 fragments of code.

Other methods


		public virtual IReflectClass ForObject(object obj)
		{
			return Reflector().ForObject(obj);
		}

		public virtual IReflectClass ForClass(Type clazz)
		{
			return Reflector().ForClass(clazz);
		}

		private IReflectArray ArrayReflector()
		{
			return Reflector().Array();
		}

		//		return _container.reflector().array();
		private IReflector Reflector()
		{
			return _container == null ? _reflector : _container.Reflector();
		}

		public virtual void CopyState(object to, object from)
		{
			IReflectClass fromClass = Reflector().ForObject(from);
			// FIXME: We need to get the classes parents fields copied too.
			foreach (IReflectField f in fromClass.GetDeclaredFields())
			{
				if (f.IsStatic())
				{
					continue;
				}
				f.Set(to, f.Get(from));
			}
		}

        [Test]
        public void Resolve_Unknown_ReturnsNull()
        {
            Assert.IsNull(Reflector.Resolve(CodeReference.Unknown, false));
            Assert.IsNull(Reflector.Resolve(CodeReference.Unknown, true));
        }

        [Test, ExpectedArgumentOutOfRangeException]
        public void GetFunctionFromStackFrame_ShouldThrowIfLessThanZero()
        {
            Reflector.GetFunctionFromStackFrame(-1);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private IFunctionInfo GetFunctionFromStackFrame_Helper()
        {
            return Reflector.GetFunctionFromStackFrame(1);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private IFunctionInfo GetCallingFunction_Helper()
        {
            return Reflector.GetCallingFunction();
        }

        [Test]
        public void GetExecutingFunction()
        {
            IFunctionInfo r = Reflector.GetExecutingFunction();
            Assert.AreEqual("GetExecutingFunction", r.Name);
        }

        [Test]
        public void GetSourceLocation_ReturnsUnknownForNamespaces()
        {
            Assert.AreEqual(CodeLocation.Unknown, Reflector.WrapNamespace("foo").GetCodeLocation());
        }


		private void RegisterPlatformTypes()
		{
			NetTypeHandler[] handlers = Platform4.Types(_container.Reflector());
			for (int i = 0; i < handlers.Length; i++)
			{
				RegisterNetTypeHandler(handlers[i]);
			}
		}

		internal Db4objects.Db4o.Internal.ArrayType ArrayType(object obj)
		{
			IReflectClass claxx = Reflector().ForObject(obj);
			if (!claxx.IsArray())
			{
				return Db4objects.Db4o.Internal.ArrayType.None;
			}
			if (IsNDimensional(claxx))
			{
				return Db4objects.Db4o.Internal.ArrayType.MultidimensionalArray;
			}
			return Db4objects.Db4o.Internal.ArrayType.PlainArray;
		}

		private bool IsNDimensional(IReflectClass clazz)
		{
			return Reflector().Array().IsNDimensional(clazz);
		}

		private GenericReflector Reflector()
		{
			return Container().Reflector();
		}

		private IReflectClass ReflectClassFor(Type clazz)
		{
			return Container().Reflector().ForClass(clazz);
		}

        /// <summary>
        /// 获取反射器
        /// </summary>
        /// <param name="member">成员元数据</param>
        public static ICustomAttributeReflectorProvider GetReflector(MemberInfo member)
        {
            if (member is null)
                throw new ArgumentNullException(nameof(member));
            return member switch
            {
                TypeInfo typeInfo => typeInfo.GetReflector(),
                Type type => type.GetReflector(),
                FieldInfo field => field.GetReflector(),
                PropertyInfo property => property.GetReflector(),
                MethodInfo method => method.GetReflector(),
                ConstructorInfo constructor => constructor.GetReflector(),
                _ => throw new InvalidOperationException("Current MemberInfo cannot be converted to Reflector.")
            };
        }

        /// <summary>
        /// 获取反射器
        /// </summary>
        /// <param name="parameter">参数元数据</param>
        public static ICustomAttributeReflectorProvider GetReflector(ParameterInfo parameter) => parameter.GetReflector();

        /// <summary>
        /// 获取运行时类型处理器集合
        /// </summary>
        /// <param name="reflector">自定义特性反射器</param>
        public static HashSet<RuntimeTypeHandle> GetRuntimeTypeHandles(CustomAttributeReflector reflector) => CustomAttributeReflectorRuntimeTypeHandle.GetValue(reflector) as HashSet<RuntimeTypeHandle>;
        /// <summary>
        /// 校验
        /// </summary>
        private static TRequired AttrRequired<TRequired>(this TRequired value, string message) => value ?? throw new ArgumentException(message);

        /// <summary>
        /// 校验
        /// </summary>
        private static IEnumerable<TRequired> AttrRequired<TRequired>(this IEnumerable<TRequired> value, string message)
        {
            if (value is null || !value.Any())
                throw new ArgumentException(message);
            return value;
        }

        /// <summary>
        /// 消除歧义,取第一项的值
        /// </summary>
        private static TAttribute AttrDisambiguation<TAttribute>(this IEnumerable<TAttribute> value) =>
            value.FirstOrDefault();

        [Test]
        public void TestAccessField_InstancePrivate()
        {
            ReflectSampleClass1 o = new ReflectSampleClass1();
            IReflector r = Reflector.Bind(o, ReflectorPolicy.InstanceAll);
            Type t = r.GetFieldType("_name");
            Assert.IsTrue(t == typeof(string));

            object val = r.GetFieldValue("_name");
            Assert.AreEqual("sample1", val);

            Assert.IsTrue(r.ExistField("_name"));
            Assert.IsFalse(r.ExistField("_Name"));

            Assert.IsFalse(r.ExistField("V"));
        }

        [Test]
        public void TestAccessField_InstancePublic()
        {
            ReflectSampleClass1 o = new ReflectSampleClass1();
            IReflector r = Reflector.Bind(o, ReflectorPolicy.InstancePublic);
            Type t = r.GetFieldType("X");
            Assert.IsTrue(t == typeof(int));

            object val = r.GetFieldValue("X");
            Assert.AreEqual(5, val);

            Assert.IsTrue(r.ExistField("X"));
            Assert.IsFalse(r.ExistField("x"));

            r.SetFieldValue("X", 10);
            Assert.AreEqual(10, o.X);
        }

        [Test]
        public void TestAccessField_Type()
        {
            IReflector r = Reflector.Bind(typeof(ReflectSampleClass1), ReflectorPolicy.TypeAll);
            Assert.IsTrue(r.ExistField("V"));
            Assert.IsFalse(r.ExistField("v"));
        }

        [Test]
        public void TestAccessProperty_InstancePrivate()
        {
            ReflectSampleClass1 o = new ReflectSampleClass1();
            IReflector r = Reflector.Bind(o, ReflectorPolicy.InstanceAllIgnoreCase);
            Type t = r.GetPropertyType("Name");
            Assert.IsTrue(t == typeof(string));

            object val = r.GetPropertyValue("Name");
            Assert.AreEqual("sample1", val);

            Assert.IsTrue(r.ExistProperty("name"));
            Assert.IsTrue(r.ExistProperty("Name"));

            Assert.IsFalse(r.ExistProperty("P"));
        }

        [Test]
        public void TestAccessProperty_InstancePublic()
        {
            ReflectSampleClass1 o = new ReflectSampleClass1();
            IReflector r = Reflector.Bind(o, ReflectorPolicy.InstancePublicIgnoreCase);
            Type t = r.GetPropertyType("count");
            Assert.IsTrue(t == typeof(int));

            object val = r.GetPropertyValue("Count");
            Assert.AreEqual(3, val);

            Assert.IsTrue(r.ExistProperty("count"));
            Assert.IsTrue(r.ExistProperty("Count"));

            r.SetPropertyValue("count", 10);
            Assert.AreEqual(10, o.Count);
        }

        [Test]
        public void TestAccessProperty_Type()
        {
            IReflector r = Reflector.Bind(typeof(ReflectSampleClass1), ReflectorPolicy.TypeAllIgnoreCase);
            Assert.IsTrue(r.ExistProperty("P"));
            Assert.IsTrue(r.ExistProperty("p"));
        }


        [SetUp]
        public void Init()
        {
            SampleClass sc = new SampleClass();
            _reflector = new Reflector(sc);
        }

        [Test]
        public void PrivateTest()
        {
            object result = _reflector.RunPrivateMethod("PrivateIntWithNoParam");
            Assert.AreEqual(5, result);
        }

        [Test]
        public void PrivateTestWithNullTest()
        {
            object result = _reflector.RunPrivateMethod("PrivateIntWithNoParam", null);
            Assert.AreEqual(5, result);
        }

        [Test]
        public void PrivateTestWithIntParamTest()
        {
            object result = _reflector.RunPrivateMethod("PrivateIntWithIntParam", 5);
            Assert.AreEqual(5, result);
        }

        [Test]
        public void PrivateOverloadedTests()
        {
            string result = (string)_reflector.RunPrivateMethod("PrivateOverloaded");
            Assert.AreEqual("Test", result);

            string result2 = (string)_reflector.RunPrivateMethod("PrivateOverloaded", result);
            Assert.AreEqual(result, result2);
        }

        [Test]
        public void PrivateVoidWithNoParamTest()
        {
            object result = _reflector.RunPrivateMethod("PrivateVoidWithNoParam");
            Assert.IsNull(result);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("----------------------------------------------------class1--------------------------------");
            Vector vc = new Vector(1, 2, 3, 4, 5, 6);
            Console.WriteLine(Reflector.GetAssemblyInfo(vc.GetType()));
            if (Reflector.IsPublishConstructors(vc.GetType())) Console.WriteLine("Class has constructor...");
            else Console.WriteLine("Constructor in clas not found...");
            Console.WriteLine("Methods:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetMetodsInfo(vc.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Fields:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetFieldInfo(vc.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Interfaces:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetInterfaceInfo(vc.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Reflector.OutputMetodsNameFromParamType(vc.GetType());


            Console.WriteLine("----------------------------------------------------class2--------------------------------");
            //-----------------------------------------
            Owner ow = new Owner();
            Console.WriteLine(Reflector.GetAssemblyInfo(ow.GetType()));
            if (Reflector.IsPublishConstructors(ow.GetType())) Console.WriteLine("Class has constructor...");
            else Console.WriteLine("Constructor in clas not found...");
            Console.WriteLine("Methods:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetMetodsInfo(ow.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Fields:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetFieldInfo(ow.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Interfaces:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetInterfaceInfo(ow.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Reflector.OutputMetodsNameFromParamType(ow.GetType());

            Console.WriteLine("----------------------------------------------------standart class--------------------------------");
            List<int> l = new List<int> { 1,2,3,4,5,6,7,8};
            Console.WriteLine(Reflector.GetAssemblyInfo(l.GetType()));
            if (Reflector.IsPublishConstructors(l.GetType())) Console.WriteLine("Class has constructor...");
            else Console.WriteLine("Constructor in clas not found...");
            Console.WriteLine("Methods:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetMetodsInfo(l.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Fields:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetFieldInfo(l.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Console.WriteLine("Interfaces:");
            Console.WriteLine("------------------------------------");
            foreach (var i in Reflector.GetInterfaceInfo(l.GetType())) Console.WriteLine(i);
            Console.WriteLine("------------------------------------");
            Reflector.OutputMetodsNameFromParamType(l.GetType());
            object[] param = new object[1];
            using (FileStream fstream = File.OpenRead($"data.txt"))
            {
                // преобразуем строку в байты
                byte[] array = new byte[fstream.Length];
                // считываем данные
                fstream.Read(array, 0, array.Length);
                // декодируем байты в строку
                string textFromFile = System.Text.Encoding.Default.GetString(array);
                param[0] = Convert.ToInt32(textFromFile);
            }
            Reflector.Invoke(l, "Add", param);
            Random rand = new Random();
            param[0] = rand.Next();
            Reflector.Invoke(l, "Add", param);
           
            Console.ReadLine();
        }


        [SetUp]
        public void Setup()
        {
            _sampleObject = new TestSample();    
        }

        #region Create Instance
        [Test]
        public void CreateInstanceByAssemblyNameAndClassWithDefaultConstructo()
        {
            string className = "System.Number";
            object obj = Reflector.CreateInstance(MSCorLibAssembly, className);
            Assert.IsNotNull(obj);
            Assert.AreEqual(true, Reflector.InvokeMethod(AccessModifier.Default, obj, "IsWhite", ' '));
            Assert.AreEqual(false, Reflector.InvokeMethod(AccessModifier.Default, obj, "IsWhite", 'V'));
        }

        [Test]
        public void CreateInstanceByAssemblyNameAndClassWithParametizedConstructor()
        {
            string className = "System.Collections.KeyValuePairs";
            object obj = Reflector.CreateInstance(MSCorLibAssembly, className, 1, 'A');
            Assert.IsNotNull(obj);
            Assert.AreEqual(1, Reflector.GetProperty(obj, "Key"));
            Assert.AreEqual('A', Reflector.GetProperty(obj, "Value"));
        }
        #endregion

        #region Field Tests
        [Test]
        public void GetPublicField_DefaultAccessibility()
        {
            Assert.AreEqual("MbUnit Rocks!!!", Reflector.GetField(_sampleObject, "publicString"));
        }

        [Test]
        public void GetPrivateFieldFromBaseClass()
        {
            Assert.AreEqual("Base var", Reflector.GetField(_sampleObject, "_baseString"));
        }

        [Test]
        [ExpectedException(typeof(ReflectionException))]
        public void TryToGetBaseClassFieldButSettingLookInBaseToFalse()
        {
            Reflector.GetField(AccessModifier.NonPublic, _sampleObject, "_baseString", false);
        }

        
        private void ReflectInternal(ProtocolReflector[] reflectors) {
            description = new ServiceDescription();
            description.TargetNamespace = serviceAttr.Namespace;
            ServiceDescriptions.Add(description);

            service = new Service();
            string name = serviceAttr.Name;
            if (name == null || name.Length == 0)
                name = serviceType.Name;
            service.Name = XmlConvert.EncodeLocalName(name);

            if (serviceAttr.Description != null && serviceAttr.Description.Length > 0)
                service.Documentation = serviceAttr.Description;
            description.Services.Add(service);

            reflectionContext = new Hashtable();
            exporter = new XmlSchemaExporter(description.Types.Schemas);
            importer = SoapReflector.CreateXmlImporter(serviceAttr.Namespace, SoapReflector.ServiceDefaultIsEncoded(serviceType));
            WebMethodReflector.IncludeTypes(methods, importer);

            for (int i = 0; i < reflectors.Length; i++) {
                reflectors[i].Reflect();
            }
        }

        /// <include file='doc\ServiceDescriptionReflector.uex' path='docs/doc[@for="ServiceDescriptionReflector.Reflect"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Reflect(Type type, string url) {
            serviceType = type;
            serviceUrl = url;
            
            serviceAttr = WebServiceReflector.GetAttribute(type);

            methods = WebMethodReflector.GetMethods(type);
            CheckForDuplicateMethods(methods);

            descriptionsWithPost = descriptions;
            schemasWithPost = schemas;

            if (reflectorsWithPost != null) {
                ReflectInternal(reflectorsWithPost);

                descriptions = new ServiceDescriptionCollection();
                schemas = new XmlSchemas();
            }
            
            ReflectInternal(reflectors);

            if (serviceAttr.Description != null && serviceAttr.Description.Length > 0)
                ServiceDescription.Documentation = serviceAttr.Description;

            // need to preprocess all exported schemas to make sure that IXmlSerializable schemas are Merged and the resulting set is valid
            ServiceDescription.Types.Schemas.Compile(null, false);

            if (ServiceDescriptions.Count > 1) {
                // if defining interfaces, we move all schemas to the external collection
                // since the types therein may be referenced from any of the sdls
                Schemas.Add(ServiceDescription.Types.Schemas);
                ServiceDescription.Types.Schemas.Clear();
            }
            else if (ServiceDescription.Types.Schemas.Count > 0) {
                XmlSchema[] descriptionSchemas = new XmlSchema[ServiceDescription.Types.Schemas.Count];
                ServiceDescription.Types.Schemas.CopyTo(descriptionSchemas, 0);
                foreach (XmlSchema schema in descriptionSchemas) {
                    // we always move dataset schemas to the external schema's collection.
                    if (XmlSchemas.IsDataSet(schema)) {
                        ServiceDescription.Types.Schemas.Remove(schema);
                        Schemas.Add(schema);
                    }
                }
            }
        }

        void CheckForDuplicateMethods(LogicalMethodInfo[] methods) {
            Hashtable messageNames = new Hashtable();
            foreach (LogicalMethodInfo method in methods) {
                WebMethodAttribute attribute = method.MethodAttribute;
                string messageName = attribute.MessageName;
                if (messageName.Length == 0) messageName = method.Name;
                string key = method.Binding == null ? messageName : method.Binding.Name + "." + messageName;
                LogicalMethodInfo existingMethod = (LogicalMethodInfo)messageNames[key];
                if (existingMethod != null) {
                    throw new InvalidOperationException(Res.GetString(Res.BothAndUseTheMessageNameUseTheMessageName3, method, existingMethod, XmlConvert.EncodeLocalName(messageName)));
                }
                messageNames.Add(key, method);
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("\nTask1");
            Passenger pass1 = new Passenger("Mark", "Moscow") { };
            Type type1 = pass1.GetType();
            Console.WriteLine($"\nТип: {type1}");

            Console.WriteLine($"\n{type1} Сборка :");
            Reflector.AssemblyName(pass1);

            Console.WriteLine($"\n{type1} Конструкторы:");
            Reflector.PublicConstructors(pass1);

            Console.WriteLine($"\n{type1} Методы:");
            Reflector.Methods(pass1);

            Console.WriteLine($"\n{type1} Свойства:");
            Reflector.Properties(pass1);

            Console.WriteLine($"\n{type1} Поля:");
            Reflector.Fields(pass1);
            
            Console.WriteLine($"\n{type1} Интерфейсы:");
            Reflector.Interfaces(pass1);

            string p = "String";
            Console.WriteLine($"\n{type1} Методы с параметром {p}:");
            Reflector.MethodsByParametr(pass1, p);

            Console.WriteLine($"\nВызывыем метод:");
            Reflector.Invoke(pass1,"Remake", Reflector.ParamsGenerater("Lab12.Passenger", "Remake"));
            
            Console.WriteLine($"\nВызывыем метод:");
            Reflector.Invoke(pass1,"Remake", Reflector.FileRead("Lab12.Passenger", "Remake"));

            Book<int,string> book1 = new Book<int, string>(2, "book1");
            Type type2 = book1.GetType();
            Console.WriteLine($"\nТип: {type2}");

            Console.WriteLine($"\n{type2} Сборка :");
            Reflector.AssemblyName(book1);

            Console.WriteLine($"\n{type2} Конструкторы:");
            Reflector.PublicConstructors(book1);

            Console.WriteLine($"\n{type2} Методы:");
            Reflector.Methods(book1);

            Console.WriteLine($"\n{type2} Свойства:");
            Reflector.Properties(book1);

            Console.WriteLine($"\n{type2} Поля:");
            Reflector.Fields(book1);

            Console.WriteLine($"\n{type2} Интерфейсы:");
            Reflector.Interfaces(book1);

            string p2 = "Int32";
            Console.WriteLine($"\n{type2} Методы с параметром {p2}:");
            Reflector.MethodsByParametr(book1, p2);

            Console.WriteLine($"\nВызывыем метод:");
            Reflector.Invoke(book1, "BookRename", Reflector.ParamsGenerater("Lab12.Book`2[System.Int32,System.String]", "BookRename"));

            Console.WriteLine($"\nВызывыем метод:");
            Reflector.Invoke(book1, "BookRename", Reflector.FileRead("Lab12.Book`2[System.Int32,System.String]", "BookRename"));

            Assembly.LoadFrom(@"C:\z\Visual Studio Projects\OOP\LibraryAirline\LibraryAirline\obj\Debug\LibraryAirline.dll");

            Console.WriteLine("\nTask2");
            Console.WriteLine($"Создаём объект:");
            Type type3 = pass1.GetType();
            Reflector.Create(type3);
            

        }

Gallio.Common.Reflection.Reflector : Object

Methods :

public static IReflectionPolicy get_NativeReflectionPolicy()
public static ICodeElementInfo Resolve(CodeReference reference = , Boolean throwOnError = )
public static IAssemblyInfo Wrap(Assembly target = )
public static INamespaceInfo WrapNamespace(String name = )
public static ITypeInfo Wrap(Type target = )
public static IList<ITypeInfo> Wrap(IList<Type> targets = )
public static IMemberInfo Wrap(MemberInfo target = )
public static IFunctionInfo Wrap(MethodBase target = )
public static IConstructorInfo Wrap(ConstructorInfo target = )
public static IMethodInfo Wrap(MethodInfo target = )
public static IPropertyInfo Wrap(PropertyInfo target = )
public static IFieldInfo Wrap(FieldInfo target = )
public static IEventInfo Wrap(EventInfo target = )
public static IParameterInfo Wrap(ParameterInfo target = )
public static IAttributeInfo Wrap(Attribute target = )
public static IFunctionInfo GetExecutingFunction()
public static IFunctionInfo GetCallingFunction()
public static IFunctionInfo GetFunctionFromStackFrame(Int32 framesToSkip = )
public static Boolean IsUnresolved(Assembly target = )
public static Boolean IsUnresolved(MemberInfo target = )
public static Boolean IsUnresolved(ParameterInfo target = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()