Csharp/C Sharp/Development Class/Reflection Assembly
Содержание
- 1 Create an object using reflection
- 2 Deeper Reflection: Invoking Functions
- 3 Demonstrate dynamically invoking an object
- 4 Demonstrate typeof
- 5 Demonstrate using Type class to discover information about a class
- 6 Get all fields from a class
- 7 Get all implemented interface from a class
- 8 Get all methods from a class
- 9 Get all properties from a class
- 10 Get Method Paramemters
- 11 Get type infomation: base type, is abstract, is com object, is sealed, is class
- 12 Illustrates creation of an application domain
- 13 Illustrates runtime type invocation
- 14 Illustrates unloading an application domain
- 15 Locate an assembly, determine types, and create an object using reflection
- 16 Uses an object in another application domain
- 17 Uses reflection to execute a class method indirectly
- 18 Uses reflection to show the inherited members of a class
- 19 Using reflection to get information about an assembly
- 20 Utilize MyClass without assuming any prior knowledge
Create an object using reflection
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Create an object using reflection.
using System; using System.Reflection;
class MyClass {
int x; int y; public MyClass(int i) { Console.WriteLine("Constructing MyClass(int, int). "); x = y = i; } public MyClass(int i, int j) { Console.WriteLine("Constructing MyClass(int, int). "); x = i; y = j; show(); } public int sum() { return x+y; } public bool isBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void set(int a, int b) { Console.Write("Inside set(int, int). "); x = a; y = b; show(); } // Overload set. public void set(double a, double b) { Console.Write("Inside set(double, double). "); x = (int) a; y = (int) b; show(); } public void show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); }
}
public class InvokeConsDemo {
public static void Main() { Type t = typeof(MyClass); int val; // Get constructor info. ConstructorInfo[] ci = t.GetConstructors(); Console.WriteLine("Available constructors: "); foreach(ConstructorInfo c in ci) { // Display return type and name. Console.Write(" " + t.Name + "("); // Display parameters. ParameterInfo[] pi = c.GetParameters(); for(int i=0; i < pi.Length; i++) { Console.Write(pi[i].ParameterType.Name + " " + pi[i].Name); if(i+1 < pi.Length) Console.Write(", "); } Console.WriteLine(")"); } Console.WriteLine(); // Find matching constructor. int x; for(x=0; x < ci.Length; x++) { ParameterInfo[] pi = ci[x].GetParameters(); if(pi.Length == 2) break; } if(x == ci.Length) { Console.WriteLine("No matching constructor found."); return; } else Console.WriteLine("Two-parameter constructor found.\n"); // Construct the object. object[] consargs = new object[2]; consargs[0] = 10; consargs[1] = 20; object reflectOb = ci[x].Invoke(consargs); Console.WriteLine("\nInvoking methods on reflectOb."); Console.WriteLine(); MethodInfo[] mi = t.GetMethods(); // Invoke each method. foreach(MethodInfo m in mi) { // Get the parameters ParameterInfo[] pi = m.GetParameters(); if(m.Name.rupareTo("set")==0 && pi[0].ParameterType == typeof(int)) { // This is set(int, int). object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if(m.Name.rupareTo("set")==0 && pi[0].ParameterType == typeof(double)) { // This is set(double, double). object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } else if(m.Name.rupareTo("sum")==0) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("sum is " + val); } else if(m.Name.rupareTo("isBetween")==0) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); } else if(m.Name.rupareTo("show")==0) { m.Invoke(reflectOb, null); } } }
}
</source>
Deeper Reflection: Invoking Functions
<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\Invoking Functions // copyright 2000 Eric Gunnerson // file=driver.cs // compile with: csc driver.cs iprocess.cs using System; using System.Reflection; using MamaSoft; public class Deeper ReflectionInvokingFunctions {
public static void ProcessAssembly(string aname) { Console.WriteLine("Loading: {0}", aname); Assembly a = Assembly.LoadFrom (aname); // walk through each type in the assembly foreach (Type t in a.GetTypes()) { // if it"s a class, it might be one that we want. if (t.IsClass) { Console.WriteLine(" Found Class: {0}", t.FullName); // check to see if it implements IProcess if (t.GetInterface("IProcess") == null) continue; // it implements IProcess. Create an instance // of the object. object o = Activator.CreateInstance(t); // create the parameter list, call it, // and print out the return value. Console.WriteLine(" Calling Process() on {0}", t.FullName); object[] args = new object[] {55}; object result; result = t.InvokeMember("Process", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, args); Console.WriteLine(" Result: {0}", result); } } } public static void Main(String[] args) { foreach (string arg in args) ProcessAssembly(arg); }
}
//======================================================= // 36 - Deeper into C#\Deeper Reflection\Invoking Functions // copyright 2000 Eric Gunnerson // file=IProcess.cs namespace MamaSoft {
interface IProcess { string Process(int param); }
} //======================================================= // 36 - Deeper into C#\Deeper Reflection\Invoking Functions // copyright 2000 Eric Gunnerson // file=process2.cs // compile with: csc /target:library process2.cs iprocess.cs using System; namespace MamaSoft {
class Processor2: IProcess { Processor2() {} public string Process(int param) { Console.WriteLine("In Processor2.Process(): {0}", param); return("Shiver me timbers! "); } } class Unrelated { }
} //======================================================== // 36 - Deeper into C#\Deeper Reflection\Invoking Functions // copyright 2000 Eric Gunnerson // file=process1.cs // compile with: csc /target:library process1.cs iprocess.cs using System; namespace MamaSoft {
class Processor1: IProcess { Processor1() {} public string Process(int param) { Console.WriteLine("In Processor1.Process(): {0}", param); return("Raise the mainsail! "); } }
}
</source>
Demonstrate dynamically invoking an object
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// Invoke.cs -- Demonstrate dynamically invoking an object // // Compile this program with the following command line: // C:>csc Invoke.cs using System; using System.Reflection; namespace nsReflection {
public class Invoke { static public void Main () { // Load the Circle assembly. Assembly asy = null; try { asy = Assembly.Load ("Circle"); } catch (Exception e) { Console.WriteLine (e.Message); return; } // Parameter array for a POINT object. object [] parmsPoint = new object [2] {15, 30}; // Parameter array for a clsCircle object. object [] parmsCircle = new object [3] {100, 15, 30}; // Get the type of clsCircle and create an instance of it. Type circle = asy.GetType("nsCircle.clsCircle"); object obj = Activator.CreateInstance (circle, parmsCircle); // Get the property info for the area and show the area PropertyInfo p = circle.GetProperty ("Area"); Console.WriteLine ("The area of the circle is " + p.GetValue(obj, null)); // Get the POINT type and create an instance of it Type point = asy.GetType("nsCircle.POINT"); object pt = Activator.CreateInstance (point, parmsPoint); // Show the point using object"s ToString() method Console.WriteLine ("The point is " + pt.ToString ()); } }
}
</source>
Demonstrate typeof
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Demonstrate typeof.
using System; using System.IO;
public class UseTypeof {
public static void Main() { Type t = typeof(StreamReader); Console.WriteLine(t.FullName); if(t.IsClass) Console.WriteLine("Is a class."); if(t.IsAbstract) Console.WriteLine("Is abstract."); else Console.WriteLine("Is concrete."); }
}
</source>
Demonstrate using Type class to discover information about a class
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// GetType.cs -- Demonstrate using Type class to discover // information about a class // // Compile this program with the following command line: // C:>csc GetType.cs using System; using System.Reflection; namespace nsReflection {
class clsEmployee { public clsEmployee (string First, string Last, string Zip, int ID) { FirstName = First; LastName = Last; EmployeeID = ID; ZipCode = Zip; } public string FirstName; public string LastName; public string ZipCode; public int EmployeeID; public string Name { get {return (FirstName + " " + LastName);} } public string Zip { get {return (ZipCode);} } public int ID { get {return (EmployeeID);} } static public int CompareByName (object o1, object o2) { clsEmployee emp1 = (clsEmployee) o1; clsEmployee emp2 = (clsEmployee) o2; return (String.rupare (emp1.LastName, emp2.LastName)); } static public int CompareByZip (object o1, object o2) { clsEmployee emp1 = (clsEmployee) o1; clsEmployee emp2 = (clsEmployee) o2; return (String.rupare (emp1.ZipCode, emp2.ZipCode)); } static public int CompareByID (object o1, object o2) { clsEmployee emp1 = (clsEmployee) o1; clsEmployee emp2 = (clsEmployee) o2; return (emp1.EmployeeID - emp2.EmployeeID); } } public class GetType { static public void Main () { Type t = typeof(clsEmployee); if (t == null) { Console.WriteLine ("t is null"); return; } Console.WriteLine ("Class clsEmployee is a member of the {0} namespace", t.Namespace); Console.WriteLine ("\r\nMethods in clsEmployee:"); MethodInfo [] methods = t.GetMethods (); foreach (MethodInfo m in methods) Console.WriteLine ("\t" + m.Name); Console.WriteLine ("\r\nProperties in clsEmployee:"); PropertyInfo [] props = t.GetProperties (); foreach (PropertyInfo p in props) Console.WriteLine ("\t" + p.Name); Console.WriteLine ("\r\nFields in clsEmployee:"); FieldInfo [] fields = t.GetFields (); foreach (FieldInfo f in fields) Console.WriteLine ("\t" + f.Name); } }
}
</source>
Get all fields from a class
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { TheType.MyClass aClass = new TheType.MyClass(); Type t = aClass.GetType(); FieldInfo[] fi = t.GetFields(); foreach(FieldInfo field in fi) Console.WriteLine("Field: {0}", field.Name); }
}
namespace TheType {
public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } public class MyClass: IFaceOne, IFaceTwo { public int myIntField; public string myStringField; private double myDoubleField = 0; public double getMyDouble(){ return myDoubleField; } public void myMethod(int p1, string p2) { } public int MyProp { get { return myIntField; } set { myIntField = value; } } public void MethodA() {} public void MethodB() {} }
}
</source>
Get all implemented interface from a class
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { TheType.MyClass aClass = new TheType.MyClass(); Type t = aClass.GetType(); Type[] ifaces = t.GetInterfaces(); foreach(Type i in ifaces) Console.WriteLine("Interface: {0}", i.Name); }
}
namespace TheType {
public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } public class MyClass: IFaceOne, IFaceTwo { public int myIntField; public string myStringField; private double myDoubleField = 0; public double getMyDouble(){ return myDoubleField; } public void myMethod(int p1, string p2) { } public int MyProp { get { return myIntField; } set { myIntField = value; } } public void MethodA() {} public void MethodB() {} }
}
</source>
Get all methods from a class
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { TheType.MyClass aClass = new TheType.MyClass(); Type t = aClass.GetType(); MethodInfo[] mi = t.GetMethods(); foreach(MethodInfo m in mi) Console.WriteLine("Method: {0}", m.Name); }
}
namespace TheType {
public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } public class MyClass: IFaceOne, IFaceTwo { public int myIntField; public string myStringField; private double myDoubleField = 0; public double getMyDouble(){ return myDoubleField; } public void myMethod(int p1, string p2) { } public int MyProp { get { return myIntField; } set { myIntField = value; } } public void MethodA() {} public void MethodB() {} }
}
</source>
Get all properties from a class
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { TheType.MyClass aClass = new TheType.MyClass(); Type t = aClass.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach(PropertyInfo prop in pi) Console.WriteLine("Prop: {0}", prop.Name); }
}
namespace TheType {
public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } public class MyClass: IFaceOne, IFaceTwo { public int myIntField; public string myStringField; private double myDoubleField = 0; public double getMyDouble(){ return myDoubleField; } public void myMethod(int p1, string p2) { } public int MyProp { get { return myIntField; } set { myIntField = value; } } public void MethodA() {} public void MethodB() {} }
}
</source>
Get Method Paramemters
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { Assembly a = null; AssemblyName asmName; asmName = new AssemblyName(); asmName.Name = "Test"; Version v = new Version("1.0.454.30104"); asmName.Version = v; a = Assembly.Load(asmName); Type testClassName = a.GetType("Test"); MethodInfo mi = testClassName.GetMethod("Main"); Console.WriteLine("Here are the params for {0}", mi.Name); // Show number of params. ParameterInfo[] myParams = mi.GetParameters(); Console.WriteLine("Method has {0} params", myParams.Length); // Show info about param. foreach(ParameterInfo pi in myParams) { Console.WriteLine("Param name: {0}", pi.Name); Console.WriteLine("Position in method: {0}", pi.Position); Console.WriteLine("Param type: {0}", pi.ParameterType); } }
}
</source>
Get type infomation: base type, is abstract, is com object, is sealed, is class
<source lang="csharp"> using System; using System.Reflection;
public class Test {
public static void Main(string[] args) { TheType.MyClass aClass = new TheType.MyClass(); Type t = aClass.GetType(); Console.WriteLine("Full name is: {0}", t.FullName); Console.WriteLine("Base is: {0}", t.BaseType); Console.WriteLine("Is it abstract? {0}", t.IsAbstract); Console.WriteLine("Is it a COM object? {0}", t.IsCOMObject); Console.WriteLine("Is it sealed? {0}", t.IsSealed); Console.WriteLine("Is it a class? {0}", t.IsClass); }
}
namespace TheType {
public interface IFaceOne { void MethodA(); } public interface IFaceTwo { void MethodB(); } public class MyClass: IFaceOne, IFaceTwo { public int myIntField; public string myStringField; private double myDoubleField = 0; public double getMyDouble(){ return myDoubleField; } public void myMethod(int p1, string p2) { } public int MyProp { get { return myIntField; } set { myIntField = value; } } public void MethodA() {} public void MethodB() {} }
}
</source>
Illustrates creation of an application domain
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example18_1.cs illustrates creation of an application domain
- /
using System; public class Example18_1 {
public static void Main() { AppDomain d = AppDomain.CreateDomain("NewDomain"); Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(d.FriendlyName); }
}
</source>
Illustrates runtime type invocation
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example17_6 illustrates runtime type invocation
- /
using System; using System.Reflection; public class Example17_6 {
public static void Main(string[] args) { RandomSupplier rs; RandomMethod rm; // iterate over all command-line arguments foreach(string s in args) { Assembly a = Assembly.LoadFrom(s); // Look through all the types in the assembly foreach(Type t in a.GetTypes()) { rs = (RandomSupplier) Attribute.GetCustomAttribute( t, typeof(RandomSupplier)); if(rs != null) { // find the method in this class. assume that // the class only contains a single method. // can"t use GetMethod() because we don"t know // what the method is named foreach(MethodInfo m in t.GetMethods()) { rm = (RandomMethod) Attribute.GetCustomAttribute( m, typeof(RandomMethod)); if(rm != null) { // create an instance of the class Object o = Activator.CreateInstance(t); // create an empty arguments array Object[] aa = new Object[0]; // invoke the method int i = (int) m.Invoke(o, aa); Console.WriteLine("Class {0} in {1} returned {2}", t, s, i); } } } } } }
} /////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////\ /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example17_5a compiles into a library defining the RamdomSupplier attribute and the RandomMethod attribute
- /
using System; // declare an attribute named RandomSupplier [AttributeUsage(AttributeTargets.Class)] public class RandomSupplier : Attribute {
public RandomSupplier() { // doesn"t have to do anything // we just use this attribute to mark selected classes }
} // declare an attribute named RandomMethod [AttributeUsage(AttributeTargets.Method )] public class RandomMethod : Attribute {
public RandomMethod() { // doesn"t have to do anything // we just use this attribute to mark selected methods }
} //=================================================== /*
Example17_5b implements one class to supply random numbers
- /
// flag the class as a random supplier [RandomSupplier] public class OriginalRandom {
[RandomMethod] public int GetRandom() { return 5; }
} //=================================================== /*
Example17_5c implements one class to supply random numbers
- /
using System; // flag the class as a random supplier [RandomSupplier] public class NewRandom {
[RandomMethod] public int ImprovedRandom() { Random r = new Random(); return r.Next(1, 100); }
} // this class has nothing to do with random numbers public class AnotherClass {
public int NotRandom() { return 1; }
} //=================================================== /*
Example17_5d illustrates runtime type discovery
- /
using System; using System.Reflection; class Example17_5d {
public static void Main(string[] args) { RandomSupplier rs; RandomMethod rm; // iterate over all command-line arguments foreach(string s in args) { Assembly a = Assembly.LoadFrom(s); // Look through all the types in the assembly foreach(Type t in a.GetTypes()) { rs = (RandomSupplier) Attribute.GetCustomAttribute( t, typeof(RandomSupplier)); if(rs != null) { Console.WriteLine("Found RandomSupplier class {0} in {1}", t, s); foreach(MethodInfo m in t.GetMethods()) { rm = (RandomMethod) Attribute.GetCustomAttribute( m, typeof(RandomMethod)); if(rm != null) { Console.WriteLine("Found RandomMethod method {0}" , m.Name ); } } } } } }
}
</source>
Illustrates unloading an application domain
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example18_4.cs illustrates unloading an application domain
- /
using System; using System.Runtime.Remoting; using System.Reflection; public class Example18_4 {
public static void Main() { // create a new appdomain AppDomain d = AppDomain.CreateDomain("NewDomain"); // load an instance of the SimpleObject class ObjectHandle hobj = d.CreateInstance("Example18_2", "SimpleObject"); // use a local variable to access the object SimpleObject so = (SimpleObject) hobj.Unwrap(); Console.WriteLine(so.ToUpper("make this uppercase")); // unload the application domain AppDomain.Unload(d); Console.WriteLine(so.ToUpper("make this uppercase")); }
}
//=================================================== /*
Example18_2.cs defines a simple object to create
- /
using System; [Serializable] public class SimpleObject {
public String ToUpper(String inString) { return(inString.ToUpper()); }
}
</source>
Locate an assembly, determine types, and create an object using reflection
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
/* Locate an assembly, determine types, and create
an object using reflection. */
using System; using System.Reflection;
public class ReflectAssemblyDemo {
public static void Main() { int val; // Load the MyClasses.exe assembly. Assembly asm = Assembly.LoadFrom("MyClasses.exe"); // Discover what types MyClasses.exe contains. Type[] alltypes = asm.GetTypes(); foreach(Type temp in alltypes) Console.WriteLine("Found: " + temp.Name); Console.WriteLine(); // Use the first type, which is MyClass in this case. Type t = alltypes[0]; // use first class found Console.WriteLine("Using: " + t.Name); // Obtain constructor info. ConstructorInfo[] ci = t.GetConstructors(); Console.WriteLine("Available constructors: "); foreach(ConstructorInfo c in ci) { // Display return type and name. Console.Write(" " + t.Name + "("); // Display parameters. ParameterInfo[] pi = c.GetParameters(); for(int i=0; i < pi.Length; i++) { Console.Write(pi[i].ParameterType.Name + " " + pi[i].Name); if(i+1 < pi.Length) Console.Write(", "); } Console.WriteLine(")"); } Console.WriteLine(); // Find matching constructor. int x; for(x=0; x < ci.Length; x++) { ParameterInfo[] pi = ci[x].GetParameters(); if(pi.Length == 2) break; } if(x == ci.Length) { Console.WriteLine("No matching constructor found."); return; } else Console.WriteLine("Two-parameter constructor found.\n"); // Construct the object. object[] consargs = new object[2]; consargs[0] = 10; consargs[1] = 20; object reflectOb = ci[x].Invoke(consargs); Console.WriteLine("\nInvoking methods on reflectOb."); Console.WriteLine(); MethodInfo[] mi = t.GetMethods(); // Invoke each method. foreach(MethodInfo m in mi) { // Get the parameters ParameterInfo[] pi = m.GetParameters(); if(m.Name.rupareTo("set")==0 && pi[0].ParameterType == typeof(int)) { // This is set(int, int). object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if(m.Name.rupareTo("set")==0 && pi[0].ParameterType == typeof(double)) { // This is set(double, double). object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } else if(m.Name.rupareTo("sum")==0) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("sum is " + val); } else if(m.Name.rupareTo("isBetween")==0) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); } else if(m.Name.rupareTo("show")==0) { m.Invoke(reflectOb, null); } } }
} //================================================================ /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// A file that contains three classes. Call this file MyClasses.cs.
using System;
class MyClass {
int x; int y; public MyClass(int i) { Console.WriteLine("Constructing MyClass(int). "); x = y = i; show(); } public MyClass(int i, int j) { Console.WriteLine("Constructing MyClass(int, int). "); x = i; y = j; show(); } public int sum() { return x+y; } public bool isBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void set(int a, int b) { Console.Write("Inside set(int, int). "); x = a; y = b; show(); } // Overload set. public void set(double a, double b) { Console.Write("Inside set(double, double). "); x = (int) a; y = (int) b; show(); } public void show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); }
}
class AnotherClass {
string remark; public AnotherClass(string str) { remark = str; } public void show() { Console.WriteLine(remark); }
}
public class Demo12 {
public static void Main() { Console.WriteLine("This is a placeholder."); }
}
</source>
Uses an object in another application domain
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example18_3.cs uses an object in another application domain
- /
using System; using System.Runtime.Remoting; using System.Reflection; public class Example18_3 {
public static void Main() { // create a new appdomain AppDomain d = AppDomain.CreateDomain("NewDomain"); // load an instance of the System.Rand object ObjectHandle hobj = d.CreateInstance("Example18_2", "SimpleObject"); // use a local variable to access the object SimpleObject so = (SimpleObject) hobj.Unwrap(); Console.WriteLine(so.ToUpper("make this uppercase")); }
}
//================================================= /*
Example18_2.cs defines a simple object to create
- /
using System; [Serializable] public class SimpleObject {
public String ToUpper(String inString) { return(inString.ToUpper()); }
}
</source>
Uses reflection to execute a class method indirectly
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// Reflect2.cs -- Uses reflection to execute a class method indirectly. // // Compile this program with the following command line: // C:>csc Reflect2.cs // using System; using System.Reflection; namespace nsReflect {
class clsReflection { private double pi = 3.14159; public double Pi { get {return (pi);} } public string ShowPi () { return ("Pi = " + pi); } } public class Reflect2 { static public void Main () { clsReflection refl = new clsReflection (); Type t = refl.GetType(); MethodInfo GetPi = t.GetMethod ("ShowPi"); Console.WriteLine (GetPi.Invoke (refl, null)); } }
}
</source>
Uses reflection to show the inherited members of a class
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// Reflect.cs -- Uses reflection to show the inherited members of a class. // // Compile this program with the following command line: // C:>csc Reflect.cs // using System; using System.Reflection; namespace nsReflect {
class clsReflection { private double pi = 3.14159; public double Pi { get {return (pi);} } public string ShowPi () { return ("Pi = " + pi); } } public class Reflection { static public void Main () { clsReflection refl = new clsReflection (); Type t = refl.GetType(); Console.WriteLine ("The type of t is " + t.ToString()); MemberInfo [] members = t.GetMembers(); Console.WriteLine ("The members of t are:"); foreach (MemberInfo m in members) Console.WriteLine (" " + m); } }
}
</source>
Using reflection to get information about an assembly
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// Asy.cs -- Demonstrates using reflection to get information // about an assembly. // // Compile this program with the following command line: // C:>csc Asy.cs using System; using System.Reflection; public class Asy {
static public void Main () { Assembly asy = null; try { asy = Assembly.Load ("Circle"); } catch (Exception e) { Console.WriteLine (e.Message); return; } Type [] types = asy.GetTypes(); foreach (Type t in types) ShowTypeInfo (t); } static void ShowTypeInfo (Type t) { Console.WriteLine ("{0} is a member of the {1} namespace", t.Name, t.Namespace); Console.WriteLine ("\r\nMethods in {0}:", t.Name); MethodInfo [] methods = t.GetMethods (); foreach (MethodInfo m in methods) Console.WriteLine ("\t" + m.Name); Console.WriteLine ("\r\nProperties in {0}:", t.Name); PropertyInfo [] props = t.GetProperties (); foreach (PropertyInfo p in props) Console.WriteLine ("\t" + p.Name); Console.WriteLine ("\r\nFields in {0}:", t.Name); FieldInfo [] fields = t.GetFields (); foreach (FieldInfo f in fields) Console.WriteLine ("\t" + f.Name); }
}
</source>
Utilize MyClass without assuming any prior knowledge
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Utilize MyClass without assuming any prior knowledge.
using System; using System.Reflection;
public class ReflectAssemblyDemo1 {
public static void Main() { int val; Assembly asm = Assembly.LoadFrom("MyClasses.exe"); Type[] alltypes = asm.GetTypes(); Type t = alltypes[0]; // use first class found Console.WriteLine("Using: " + t.Name); ConstructorInfo[] ci = t.GetConstructors(); // Use first constructor found. ParameterInfo[] cpi = ci[0].GetParameters(); object reflectOb; if(cpi.Length > 0) { object[] consargs = new object[cpi.Length]; // initialize args for(int n=0; n < cpi.Length; n++) consargs[n] = 10 + n * 20; // construct the object reflectOb = ci[0].Invoke(consargs); } else reflectOb = ci[0].Invoke(null); Console.WriteLine("\nInvoking methods on reflectOb."); Console.WriteLine(); // Ignore inherited methods. MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ; // Invoke each method. foreach(MethodInfo m in mi) { Console.WriteLine("Calling {0} ", m.Name); // Get the parameters ParameterInfo[] pi = m.GetParameters(); // Execute methods. switch(pi.Length) { case 0: // no args if(m.ReturnType == typeof(int)) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("Result is " + val); } else if(m.ReturnType == typeof(void)) { m.Invoke(reflectOb, null); } break; case 1: // one arg if(pi[0].ParameterType == typeof(int)) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); else Console.WriteLine("14 is not between x and y"); } break; case 2: // two args if((pi[0].ParameterType == typeof(int)) && (pi[1].ParameterType == typeof(int))) { object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if((pi[0].ParameterType == typeof(double)) && (pi[1].ParameterType == typeof(double))) { object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } break; } Console.WriteLine(); } }
} //============================================================== /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// A file that contains three classes. Call this file MyClasses.cs.
using System;
class MyClass {
int x; int y; public MyClass(int i) { Console.WriteLine("Constructing MyClass(int). "); x = y = i; show(); } public MyClass(int i, int j) { Console.WriteLine("Constructing MyClass(int, int). "); x = i; y = j; show(); } public int sum() { return x+y; } public bool isBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void set(int a, int b) { Console.Write("Inside set(int, int). "); x = a; y = b; show(); } // Overload set. public void set(double a, double b) { Console.Write("Inside set(double, double). "); x = (int) a; y = (int) b; show(); } public void show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); }
}
class AnotherClass {
string remark; public AnotherClass(string str) { remark = str; } public void show() { Console.WriteLine(remark); }
}
public class Demo12 {
public static void Main() { Console.WriteLine("This is a placeholder."); }
}
</source>