⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chap17.lst

📁 Csharp2完全参考手册源代码 详细的说明可以在书里看到 该书是08年刚出炉很新鲜
💻 LST
📖 第 1 页 / 共 2 页
字号:
   an object using reflection. */ 
 
using System; 
using System.Reflection; 
 
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.CompareTo("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.CompareTo("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.CompareTo("sum")==0) { 
        val = (int) m.Invoke(reflectOb, null); 
        Console.WriteLine("sum is " + val); 
      } 
      else if(m.Name.CompareTo("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.CompareTo("show")==0) { 
        m.Invoke(reflectOb, null); 
      } 
    } 
 
  } 
}

listing 10
// Utilize MyClass without assuming any prior knowledge. 
 
using System; 
using System.Reflection; 
 
class ReflectAssemblyDemo { 
  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(); 
    } 
 
  } 
}

listing 11
[AttributeUsage(AttributeTargets.All)] 
public class RemarkAttribute : Attribute { 
  string pri_remark; // underlies remark property 
 
  public RemarkAttribute(string comment) { 
    pri_remark = comment; 
  } 
 
  public string remark { 
    get { 
      return pri_remark; 
    } 
  } 
} 

listing 12
// A simple attribute example. 
  
using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class RemarkAttribute : Attribute { 
  string pri_remark; // underlies remark property 
 
  public RemarkAttribute(string comment) { 
    pri_remark = comment; 
  } 
 
  public string remark { 
    get { 
      return pri_remark; 
    } 
  } 
}  
 
[RemarkAttribute("This class uses an attribute.")] 
class UseAttrib { 
  // ... 
} 
 
class AttribDemo {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    Console.Write("Remark: "); 
 
    // Retrieve the RemarkAttribute. 
    Type tRemAtt = typeof(RemarkAttribute); 
    RemarkAttribute ra = (RemarkAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.WriteLine(ra.remark); 
  }  
}

listing 13
[AttributeUsage(AttributeTargets.All)] 
public class RemarkAttribute : Attribute { 
  string pri_remark; // underlies remark property 
 
  public string supplement; // this is a named parameter 
 
  public RemarkAttribute(string comment) { 
    pri_remark = comment; 
    supplement = "None"; 
  } 
 
  public string remark { 
    get { 
      return pri_remark; 
    } 
  } 
}

listing 14
// Use a named attribute parameter. 
  
using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class RemarkAttribute : Attribute { 
  string pri_remark; // underlies remark property 
 
  public string supplement; // this is a named parameter 
 
  public RemarkAttribute(string comment) { 
    pri_remark = comment; 
    supplement = "None"; 
  } 
 
  public string remark { 
    get { 
      return pri_remark; 
    } 
  } 
}  
 
[RemarkAttribute("This class uses an attribute.", 
                 supplement = "This is additional info.")] 
class UseAttrib { 
  // ... 
} 
 
class NamedParamDemo {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    // Retrieve the RemarkAttribute. 
    Type tRemAtt = typeof(RemarkAttribute); 
    RemarkAttribute ra = (RemarkAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.Write("Remark: "); 
    Console.WriteLine(ra.remark); 
 
    Console.Write("Supplement: "); 
    Console.WriteLine(ra.supplement); 
  }  
}

listing 15
// Use a property as a named attribute parameter. 
  
using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class RemarkAttribute : Attribute { 
  string pri_remark; // underlies remark property 
 
  int pri_priority; // underlies priority property 
 
  public string supplement; // this is a named parameter 
 
  public RemarkAttribute(string comment) { 
    pri_remark = comment; 
    supplement = "None"; 
  } 
 
  public string remark { 
    get { 
      return pri_remark; 
    } 
  } 
 
  // Use a property as a named parameter. 
  public int priority { 
    get { 
      return pri_priority; 
    } 
    set { 
      pri_priority = value; 
    } 
  } 
}  
 
[RemarkAttribute("This class uses an attribute.", 
                 supplement = "This is additional info.", 
                 priority = 10)] 
class UseAttrib { 
  // ... 
} 
 
class NamedParamDemo {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    // Retrieve the RemarkAttribute. 
    Type tRemAtt = typeof(RemarkAttribute); 
    RemarkAttribute ra = (RemarkAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.Write("Remark: "); 
    Console.WriteLine(ra.remark); 
 
    Console.Write("Supplement: "); 
    Console.WriteLine(ra.supplement); 
 
    Console.WriteLine("Priority: " + ra.priority); 
  }  
}

listing 16
// Demonstrate the Conditional attribute. 
 
#define TRIAL 
 
using System; 
using System.Diagnostics; 
 
class Test { 
 
  [Conditional("TRIAL")]  
  void trial() { 
    Console.WriteLine("Trial version, not for distribution."); 
  } 
 
  [Conditional("RELEASE")]  
  void release() { 
    Console.WriteLine("Final release version."); 
  } 
 
  public static void Main() { 
    Test t = new Test(); 
 
    t.trial(); // call only if TRIAL is defined 
    t.release(); // called only if RELEASE is defined 
  } 
}

listing 17
// Demonstrate the Obsolete attribute. 
 
using System; 
 
class Test { 
 
  [Obsolete("Use myMeth2, instead.")]  
  static int myMeth(int a, int b) { 
    return a / b; 
  } 
 
  // Improved version of myMeth. 
  static int myMeth2(int a, int b) { 
    return b == 0 ? 0 : a /b; 
  } 
 
  public static void Main() { 
   // warning displayed for this 
    Console.WriteLine("4 / 3 is " + Test.myMeth(4, 3)); 
 
   // no warning here 
    Console.WriteLine("4 / 3 is " + Test.myMeth2(4, 3));  
  } 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -