Csharp/C Sharp/Reflection/Type

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call GetType for int data type

<source lang="csharp"> using System; using System.Reflection;

class TypeObjectFromInstanceApp {

   public static void Main(string[] args)
   {
       int i = 6;
       Type type = i.GetType();
       Console.WriteLine(type.Name);
   }

}

</source>


Call GetType() from StringBuilder

<source lang="csharp"> using System; using System.Text; class MainClass{

       public static void Main()
       {
           StringBuilder sb = new StringBuilder();
           Type t6 = sb.GetType();
      }

}

</source>


Call static method GetType from Type to get the Type instance

<source lang="csharp"> using System; using System.Text; class MainClass{

       public static void Main()
       {
           Type t2 = Type.GetType("System.String");
           Type t3 = Type.GetType("System.String", true);
           Type t4 = Type.GetType("system.string", true, true);
           Type t5 = Type.GetType("System.Data.DataSet, System.Data,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
      }

}

</source>


Deeper Reflection:Listing All the Types in an Assembly

<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3

  • /

// 36 - Deeper into C#\Deeper Reflection\Listing All the Types in an Assembly // copyright 2000 Eric Gunnerson using System; using System.Reflection; enum MyEnum {

   Val1,
   Val2,
   Val3

} class MyClass { } struct MyStruct { } public class ListingAlltheTypesinanAssembly {

   public static void Main(String[] args)
   {
       // list all types in the assembly that is passed
       // in as a parameter
       Assembly a = Assembly.LoadFrom (args[0]);
       Type[] types = a.GetTypes();
       
       // look through each type, and write out some information
       // about them.
       foreach (Type t in types)
       {
           Console.WriteLine ("Name: {0}", t.FullName);
           Console.WriteLine ("Namespace: {0}", t.Namespace);
           Console.WriteLine ("Base Class: {0}", t.BaseType.FullName);
       }
   }

}

      </source>


demonstrates both the instance and static GetType methods

<source lang="csharp"> using System;

class MyClass<K, V> {

   public void FunctionA(K argk, V argv) {
   }

} class XClass<T> {

   public void FunctionB(T argt) {
   }

} class Starter {

   public static void Main() {
       MyClass<int, decimal> obj = new MyClass<int, decimal>();
       Type typeClosed = obj.GetType();
       Console.WriteLine(typeClosed.ToString());
       Type typeOpen = Type.GetType("CSharpBook.XClass`1");
       Console.WriteLine(typeOpen.ToString());
       Type typeClosed2 = Type.GetType(
           "CSharpBook.MyClass`2[System.Int32, System.Decimal]");
       Console.WriteLine(typeClosed2.ToString());
   }

}

</source>


Determining the base classes and interfaces for a class.

<source lang="csharp">

using System; using System.Reflection; using System.Collections; class MainClass {

   public static void Main(string[] args) {
       if (args.Length >= 2)
           CheckBaseClass(args[0], args[1]);
   }
   public static void CheckBaseClass(string AssemblyName,string ClassName) {
       Assembly assembly = Assembly.LoadFrom(AssemblyName);
       if (assembly == null) {
           Console.WriteLine("Unable to open {0}",AssemblyName);
           return;
       }
       foreach (Type t in assembly.GetTypes()) {
           if (t.IsClass == false)
               continue;
           Type baseType = t.BaseType;
           while (baseType != null) {
               if (baseType.FullName.EndsWith(ClassName)) {
                   Console.WriteLine("Class {0} is derived from {1}",t.FullName, ClassName);
               }
               baseType = baseType.BaseType;
           }
           Type[] intfc = t.GetInterfaces();
           foreach (Type itf in intfc) {
               if (itf.FullName.EndsWith(ClassName)) {
                   Console.WriteLine("Class {0} is derived from intf {1}",t.FullName, ClassName);
               }
           }
       }
   }

}

</source>


Generic methods, like nongeneric methods, can be invoked dynamically at run time.

<source lang="csharp"> using System; using System.Reflection;

public class GenericZ<K, V, Z>

   where K : new()
   where V : new() {
   public void MethodA<A>(A argument1, Z argument2) {
       Console.WriteLine("MethodA invoked");
   }
   private K field1 = new K();
   private V field2 = new V();

} class Starter {

   static void Main() {
       Type genericType = typeof(GenericZ<,,>);
       Type[] parameters ={typeof(int),typeof(float),
               typeof(int)};
       Type closedType = genericType.MakeGenericType(parameters);
       MethodInfo openMethod = closedType.GetMethod("MethodA");
       object newObject = Activator.CreateInstance(closedType);
       parameters = new Type[] { typeof(int) };
       MethodInfo closedMethod =
           openMethod.MakeGenericMethod(parameters);
       object[] methodargs = { 2, 10 };
       closedMethod.Invoke(newObject, methodargs);
   }

}

</source>


Get Generic Type Definition

<source lang="csharp"> using System;

class MyClass<K, V> {

   public void FunctionA(K argk, V argv) {
   }

} class Starter {

   public static void Main() {
       MyClass<int, decimal> obj = new MyClass<int, decimal>();
       MyClass<string, float> obj2 = new MyClass<string, float>();
       Type closedType = obj.GetType();
       Type openType = closedType.GetGenericTypeDefinition();
       Type closedType2 = obj2.GetType();
       Type openType2 = closedType2.GetGenericTypeDefinition();
       Console.WriteLine(openType.ToString());
       Console.WriteLine(openType2.ToString());
   }

}

</source>


Get object Type Name, UnderlyingSystemType, IsClass

<source lang="csharp"> using System; using System.Reflection; class InstanceType {

 public static void Main()
 {
   String myVar = "P";
   Type t = myVar.GetType();
   Console.WriteLine("Name : {0}",t.Name);
   Console.WriteLine("Underlying System Type : {0}",t.UnderlyingSystemType);
   Console.WriteLine("Is Class : {0}",t.IsClass);
 }

}

</source>


Illustrates runtime type creation

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example17_7 illustrates runtime type creation
  • /

using System; using System.Reflection; using System.Reflection.Emit; public class Example17_7 {

   public static void Main() 
   {
       // get the current appdomain
       AppDomain ad = AppDomain.CurrentDomain;
       // create a new dynamic assembly
       AssemblyName an = new AssemblyName();
       an.Name = "DynamicRandomAssembly";
       AssemblyBuilder ab = ad.DefineDynamicAssembly(
        an, AssemblyBuilderAccess.Run);
       // create a new module to hold code in the assembly
       ModuleBuilder mb = ab.DefineDynamicModule("RandomModule");
       // create a type in the module
       TypeBuilder tb = mb.DefineType(
        "DynamicRandomClass",TypeAttributes.Public);
       // create a method of the type
       Type returntype = typeof(int);
       Type[] paramstype = new Type[0];
       MethodBuilder methb=tb.DefineMethod("DynamicRandomMethod", 
        MethodAttributes.Public, returntype, paramstype);
       // generate the MSIL
       ILGenerator gen = methb.GetILGenerator();
       gen.Emit(OpCodes.Ldc_I4, 1);
       gen.Emit(OpCodes.Ret);
       // finish creating the type and make it available
       Type t = tb.CreateType();
       // create an instance of the new type
       Object o = Activator.CreateInstance(t);
       // create an empty arguments array
       Object[] aa = new Object[0];
       // get the method and invoke it
       MethodInfo m = t.GetMethod("DynamicRandomMethod");
       int i = (int) m.Invoke(o, aa);
       Console.WriteLine("Method {0} in Class {1} returned {2}",
           m, t, i);
   }

} //============================================================= using System; public class DynamicRandomClass {

   public int DynamicRandomMethod()
   {
       return 1;
   }

}


      </source>


IsGeneric and IsGenericTypeDefinition

<source lang="csharp"> using System; using System.Reflection; public class MyClass<T, V> {

   public T membera;

} public class XClass {

   public void MethodA<T>() {
   }

} class Starter {

   static void Main() {
       Type[] types = { typeof(MyClass<,>), typeof(MyClass<int, int>) };
       bool[,] bresp = { {types[0].IsGenericType,
                              types[0].IsGenericTypeDefinition},
                             {types[1].IsGenericType,
                              types[1].IsGenericTypeDefinition}};
       Console.WriteLine("Is MyClass<,> a generic type? " + bresp[0, 0]);
       Console.WriteLine("Is MyClass<,> open? " + bresp[0, 1]);
       Console.WriteLine("Is MyClass<int,int> a generic type? " + bresp[1, 0]);
       Console.WriteLine("Is MyClass<int,int> open? " + bresp[1, 1]);
       Type tObj = typeof(XClass);
       MethodInfo method = tObj.GetMethod("MethodA");
       bool[] bMethod ={method.IsGenericMethod, method.IsGenericMethodDefinition};
       Console.WriteLine("Is XClass.MethodA<T> a generic method? " + bMethod[0]);
       Console.WriteLine("Is XClass.MethodA<T> open? " + bMethod[1]);
   }

}

</source>


Print Types

<source lang="csharp"> using System; using System.Collections; using System.Reflection; public class MainClass{

   public static void Main(){
       Assembly LoadedAsm = Assembly.LoadFrom("yourName");
       Console.WriteLine(LoadedAsm.FullName);
       Type[] LoadedTypes = LoadedAsm.GetTypes();
       if (LoadedTypes.Length == 0) {
           Console.WriteLine("No Types!");
       } else {
           foreach (Type t in LoadedTypes) {
               if (t.IsPublic) {
                   Console.WriteLine("Public ");
               } else if (t.IsNestedPublic) {
                   Console.WriteLine("Public Nested ");
               } else {
                   Console.WriteLine("Not Public ");
               }
               if (t.IsEnum) {
                   Console.WriteLine("Enum: ");
               } else if (t.IsValueType) {
                   Console.WriteLine("Struct: ");
               } else {
                   Console.WriteLine("Class: ");
               }
               Console.WriteLine("{0}", t.FullName);
           }
       }
   }

}

</source>


Query properties of a Type

<source lang="csharp"> using System; using System.Reflection;

class QueryTypesApp {

   public static void DisplaySyntax()
   {
       Console.WriteLine("\nSyntax: QueryTypes <typename>\n");
   }
  
   public static void QueryType(string typename)
   {
       try
       {
           Type type = Type.GetType(typename, true, true);
  
           Console.WriteLine("Type name: {0}", type.FullName);
           Console.WriteLine("\tHasElementType = {0}", type.HasElementType);
           Console.WriteLine("\tIsAbstract = {0}", type.IsAbstract);
           Console.WriteLine("\tIsAnsiClass = {0}", type.IsAnsiClass);
           Console.WriteLine("\tIsArray = {0}", type.IsArray);
           Console.WriteLine("\tIsAutoClass = {0}", type.IsAutoClass);
           Console.WriteLine("\tIsAutoLayout = {0}", type.IsAutoLayout);
           Console.WriteLine("\tIsByRef = {0}", type.IsByRef);
           Console.WriteLine("\tIsClass = {0}", type.IsClass);
           Console.WriteLine("\tIsCOMObject = {0}",type.IsCOMObject);
           Console.WriteLine("\tIsContextful = {0}", type.IsContextful);
           Console.WriteLine("\tIsEnum = {0}", type.IsEnum);
           Console.WriteLine("\tIsExplicitLayout = {0}",type.IsExplicitLayout);
           Console.WriteLine("\tIsImport = {0}", type.IsImport);
           Console.WriteLine("\tIsInterface = {0}", type.IsInterface);
           Console.WriteLine("\tIsLayoutSequential = {0}", type.IsLayoutSequential);
           Console.WriteLine("\tIsMarshalByRef = {0}", type.IsMarshalByRef);
           Console.WriteLine("\tIsNestedAssembly = {0}",type.IsNestedAssembly);
           Console.WriteLine("\tIsNestedFamANDAssem = {0}", type.IsNestedFamANDAssem);
           Console.WriteLine("\tIsNestedFamily = {0}", type.IsNestedFamily);
           Console.WriteLine("\tIsNestedFamORAssem = {0}",type.IsNestedFamORAssem);
           Console.WriteLine("\tIsNestedPrivate = {0}", type.IsNestedPrivate);
           Console.WriteLine("\tIsNestedPublic = {0}", type.IsNestedPublic);
           Console.WriteLine("\tIsNotPublic = {0}", type.IsNotPublic);
           Console.WriteLine("\tIsPointer = {0}", type.IsPointer);
           Console.WriteLine("\tIsPrimitive = {0}", type.IsPrimitive);
           Console.WriteLine("\tIsPublic = {0}", type.IsPublic);
           Console.WriteLine("\tIsSealed = {0}", type.IsSealed);
           Console.WriteLine("\tIsSerializable = {0}", type.IsSerializable);
           Console.WriteLine("\tIsSpecialName = {0}",type.IsSpecialName);
           Console.WriteLine("\tIsUnicodeClass = {0}", type.IsUnicodeClass);
           Console.WriteLine("\tIsValueType = {0}", type.IsValueType);
       }
       catch(System.TypeLoadException e)
       {
           Console.WriteLine("{0} is not a valid type",
                typename);
       }
   }
  
   public static void Main(string[] args)
   {
       if (1 != args.Length) DisplaySyntax();
       else QueryType(args[0]);
  
       Console.ReadLine();
   }

}

</source>


The typeName parameter is a combination of the Assembly and Type names

<source lang="csharp"> using System; using System.Reflection; class ReflectOnlyType {

   static void Main() {
       Type zType = Type.ReflectionOnlyGetType("ReflectOnlyType", false, false);
       Console.WriteLine(zType.Name);
   }

}

</source>


Type.GetConstructors

<source lang="csharp"> using System; using System.Reflection; public class Class1 {

   public static int Main() {
       Type t = typeof(MyClass);
       Console.WriteLine("Type of class: " + t);
       Console.WriteLine("Namespace: " + t.Namespace);
       ConstructorInfo[] ci = t.GetConstructors();
       Console.WriteLine("Constructors are:");
       foreach (ConstructorInfo i in ci) {
           Console.WriteLine(i);
       }
       return 0;
   }
   public class MyClass {
       public int pubInteger;
       private int _privValue;
       public MyClass() {
       }
       public MyClass(int IntegerValueIn) {
           pubInteger = IntegerValueIn;
       }
       public int Add10(int IntegerValueIn) {
           Console.WriteLine(IntegerValueIn);
           return IntegerValueIn + 10;
       }
       public int TestProperty {
           get {
               return _privValue;
           }
           set {
               _privValue = value;
           }
       }
   }

}

</source>


Type.GetGenericArguments and MethodInfo.GetGenericArguments:

<source lang="csharp"> using System;

class MyClass<K, V> {

   public void FunctionA(K argk, V argv) {
   }

} class Starter {

   public static void Main() {
       MyClass<int, decimal> obj = new MyClass<int, decimal>();
       MyClass<string, float> obj2 = new MyClass<string, float>();
       Type closedType = obj.GetType();
       Type openType = closedType.GetGenericTypeDefinition();
       Type closedType2 = obj2.GetType();
       Type openType2 = closedType2.GetGenericTypeDefinition();
       Console.WriteLine(openType.ToString());
       Console.WriteLine(openType2.ToString());
   }

}

</source>


Use GetCustomAttributes from Type to get custom attributes

<source lang="csharp">

using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public class AuthorAttribute : System.Attribute {

   private string company; // Creator"s company
   private string name;    // Creator"s name
   public AuthorAttribute(string name)
   {
       this.name = name;
       company = "";
   }
   public string Company
   {
       get { return company; }
       set { company = value; }
   }
   public string Name
   {
       get { return name; }
   }

}

[assembly: Author("Allen", Company = "Ltd.")] [Author("Allen", Company = "Objective Ltd.")] class SomeClass { } [Author("Lena")] public class SomeOtherClass { }

[Author("FirstName")] [Author("Allen", Company = "Ltd.")] class MainClass {

   public static void Main()
   {
       Type type = typeof(MainClass);
       object[] attrs = type.GetCustomAttributes(typeof(AuthorAttribute), true);
       foreach (AuthorAttribute a in attrs)
       {
           Console.WriteLine(a.Name + ", " + a.rupany);
       }
   }

}

</source>


Use Type.GetType to check the type of an object

<source lang="csharp"> using System; using System.IO; class MainClass {

   public static bool IsType(object obj, string type)
   {
       Type t = Type.GetType(type, true, true);
       return t == obj.GetType() || obj.GetType().IsSubclassOf(t);
   }
   public static void Main()
   {
       Object someObject = new StringReader("This is a StringReader");
       if (typeof(StringReader) == someObject.GetType())
       {
           Console.WriteLine("typeof: someObject is a StringReader");
       }
       if (IsType(someObject, "System.IO.TextReader"))
       {
           Console.WriteLine("GetType: someObject is a TextReader");
       }
   }

}

</source>


Use Type.IsClass to check if a type is a class

<source lang="csharp"> using System; using System.Reflection; class NameType {

 public static void Main()
 {
       Type t = Type.GetType("System.String");
   Console.WriteLine("Name : {0}",t.Name);
   Console.WriteLine("Underlying System Type : {0}",t.UnderlyingSystemType);
   Console.WriteLine("Is Class : {0}",t.IsClass);
 }

}

</source>