In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to achieve C# reflection". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
C # reflection technology is mainly based on the System.Type class and the System.Reflection.Assemble class. Through the Type class, you can access information about any data type. The Assemble class is used to access information about a given assembly or to load the assembly into the program.
I. System.Type class
The Type class is an abstract class. Whenever you instantiate a Type object, you actually instantiate a derived class of Type. Although in general derived classes only provide different overloads of various Type methods and properties, these methods and properties return the correct data for the corresponding data type, and Type has a derived class for each data type. They generally do not add new methods or properties
In general, there are three common ways to get to any given Type reference:
* use the typeof operator, whose argument is the name of the type but is not enclosed in quotation marks:
Type t = typeof (double)
* use the GetType () method, so all classes inherit this method from System.Object:
Double d = 10 × Type t = d.GetType ()
When the GetType () method is called on a variable, the returned Type object is only related to that data type and does not contain any information about the instance of that type.
* call the static method GetType () of the Type class:
Type t = Type.GetType ("System.Double")
Type is the entrance to many reflection functions, it implements many methods and properties, and the available properties are read-only: you can use Type to determine the type of data, but you cannot use it to modify it.
1.Type attribute
The properties implemented by Type fall into three categories.
* A string containing various names associated with the class:
Name: data type name
FullName: fully qualified name of the data type (including namespaces)
Namespace: the namespace name in which the data type is defined
* get the properties of the reference to the Type object:
BaseType: the direct base type of the object
UnderlyingSystemType: the type to which the Type is mapped in the .NET runtime
* Boolean attribute
IsAbstract,IsArray,IsClass,IsEnum and others determine what type of attribute Type is.
two。 Method
Most of System.Type 's methods are used to get member information for the corresponding data type: constructors, properties, methods, events, and so on. It has many ways, but they all have the same pattern. For example, get information about a method of a data type: GetMethod () and GetMethods (). The GetMethod () method returns a reference to the MethodInfo object containing the details of a specified method; GetMethods () returns an array of such references.
II. Assembly class
The Assembly class allows access to the metadata of a given assembly, and it also contains methods that can load and execute the assembly, assuming it is executable. Like the Type class, the Assembly class contains a lot of methods and properties. Only members related to the feature (/ / www.yisu.com/article/244250.htm) are introduced here, and other members can go to MSDN (https://msdn.microsoft.com/zh-cn/library/system.reflection.assembly(v=vs.100).aspx).
Before using the Assembly instance to do some work, you need to load the corresponding assembly into the running process. You can use the static method Assembly.Load () or Assembly.LoadFrom (). The name of the parameter assembly of the Load () method, which the runtime searches for in various locations, including the local directory and the global assembly cache. The argument to the LoadFrom () method is the full path name of the assembly, and it does not search for the assembly elsewhere:
Assembly assembly1 = Assembly.Load ("WhatsNewAttributes"); Assembly assembly2 = Assembly.LoadFrom ("E:\ WhatsNewAttributes\ bin\ Debug\ WhatsNewAttributes")
There are many other overloaded versions of both methods.
1. Gets the details of the types defined in the assembly
The Assembly class calls the GetType () method to get the details of all types defined in the corresponding assembly, which returns an array of System.Type references containing the details of all types:
Type [] types = assembly1.GetType (); foreach (Type t in types) {} 2. Get details of custom properties
If you need to determine what custom properties the assembly is associated with, you need to call a static method GetCustomAttributes () of the Attribute class:
Assembly assembly1 = Assembly.Load ("WhatsNewAttributes"); Attribute [] attribs = Attribute.GetCustomAttributes (assembly1)
The GetCustomAttributes method, which is used to get the properties of the assembly, has two overloaded methods: if it is called with no parameters other than a reference to the assembly, the method returns all the custom properties defined by the assembly; if you specify the second parameter, the second parameter represents a Type object of the property class, and the GetCustomAttributes method returns an array of properties of the specified property type.
All features are obtained as generic Attribute references. If you need to call any methods or properties defined for custom properties, you need to convert these reference displays to custom property classes.
If you want to get properties with methods, constructors, fields, and so on, you need to call the GetCustomAttributes () method of classes such as MethodInfo,ConstructorInfo,FieldInfo.
Here is an example to demonstrate custom properties and reflections
1. Write custom properties namespace WhatsNewAttributes {[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class LastModifiedAttribute: Attribute {private readonly DateTime _ dateModified; private readonly string _ changes; public LastModifiedAttribute (string dateModified, string changes) {_ dateModified = DateTime.Parse (dateModified) _ changes = changes;} public DateTime DateModified {get {return _ dateModified;}} public string Changes {get {return _ changes;}} public string Issues {get; set }} [AttributeUsage (AttributeTargets.Assembly)] public class SupportsWhatsNewAttribute: Attribute {} 2. Use custom features for VectorClass and its members [assembly: SupportsWhatsNew] namespace VectorClass {[LastModified ("14 Feb 2010", "IEnumerable interface implemented" + "So Vector can now be treated as a collection")] [LastModified ("10 Feb 2010") "IFormattable interface implemented" + "So Vector now responds to format specifiers N and VE")] class Vector: IFormattable, IEnumerable {public double x, y, z Public Vector (double x, double y, double z) {this.x = x; this.y = y; this.z = z } [LastModified ("10 Feb 2010", "Method added in order to provide formatting support")] public string ToString (string format, IFormatProvider formatProvider) {if (format = = null) return ToString (); string formatUpper = format.ToUpper () Switch (formatUpper) {case "N": return | | "+ Norm (). ToString () +" | |; case "VE": return String.Format ("({0v E}, {1V E}, {2V E})", x, y, z) Case "IJK": StringBuilder sb = new StringBuilder (x.ToString (), 30); sb.Append ("I +"); sb.Append (y.ToString ()); sb.Append ("j +"); sb.Append (z.ToString ()) Sb.Append ("k"); return sb.ToString (); default: return ToString ();}} public Vector (Vector rhs) {x = rhs.x; y = rhs.y Z = rhs.z;} [LastModified ("14 Feb 2010", "Method added in order to provide collection support")] public IEnumerator GetEnumerator () {return new VectorEnumerator (this) } public override string ToString () {return "(" + x + "," + y + "," + z + ")" } public double this [uint I] {get {switch (I) {case 0: return x Case 1: return y; case 2: return z; default: throw new IndexOutOfRangeException ("Attempt to retrieve Vector element" + I) }} set {switch (I) {case 0: X = value; break Case 1: y = value; break; case 2: Z = value; break Default: throw new IndexOutOfRangeException ("Attempt to set Vector element" + I) } public static bool operator = (Vector lhs, Vector rhs) {if (System.Math.Abs (lhs.x-rhs.x))
< double.Epsilon && System.Math.Abs(lhs.y - rhs.y) < double.Epsilon && System.Math.Abs(lhs.z - rhs.z) < double.Epsilon) return true; else return false; } public static bool operator !=(Vector lhs, Vector rhs) { return !(lhs == rhs); } public static Vector operator +(Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; } public static Vector operator *(double lhs, Vector rhs) { return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } public static Vector operator *(Vector lhs, double rhs) { return rhs * lhs; } public static double operator *(Vector lhs, Vector rhs) { return lhs.x * rhs.x + lhs.y + rhs.y + lhs.z * rhs.z; } public double Norm() { return x * x + y * y + z * z; } #region enumerator class [LastModified("14 Feb 2010", "Class created as part of collection support for Vector")] private class VectorEnumerator : IEnumerator { readonly Vector _theVector; // Vector object that this enumerato refers to int _location; // which element of _theVector the enumerator is currently referring to public VectorEnumerator(Vector theVector) { _theVector = theVector; _location = -1; } public bool MoveNext() { ++_location; return (_location >2)? False: true;} public object Current {get {if (_ location)
< 0 || _location >2) throw new InvalidOperationException ("The enumerator is either before the first element or" + "after the last element of theVector"); return _ theVector [(uint) _ location] }} public void Reset () {_ location =-1;}} # endregion}} 3. Get the custom properties of the assembly VectorClass and its members namespace LookUpWhatsNew {internal class WhatsNewChecker {private static readonly StringBuilder outputText = new StringBuilder (1000); private static DateTime backDateTo = new DateTime (2010, 2, 1); private static void Main () {Assembly theAssembly = Assembly.Load ("VectorClass") through reflection Attribute supportsAttribute = Attribute.GetCustomAttribute (theAssembly, typeof (SupportsWhatsNewAttribute)); string name = theAssembly.FullName; AddToMessage ("Assembly:" + name) If (supportsAttribute = = null) {AddToMessage ("This assembly does not support WhatsNew attributes"); return;} else {AddToMessage ("Defined Types:") } Type [] types = theAssembly.GetTypes (); foreach (Type definedType in types) DisplayTypeInfo (definedType); MessageBox.Show (outputText.ToString (), "What\'s New since" + backDateTo.ToLongDateString ()); Console.ReadLine () } private static void DisplayTypeInfo (Type type) {/ / make sure we only pick out classes if (! (type.IsClass)) return; AddToMessage ("\ nclass" + type.Name); Attribute [] attribs = Attribute.GetCustomAttributes (type) If (attribs.Length = = 0) AddToMessage ("No changes to this class"); else foreach (Attribute attrib in attribs) WriteAttributeInfo (attrib); MethodInfo [] methods = type.GetMethods (); AddToMessage ("CHANGES TO METHODS OF THIS CLASS:") Foreach (MethodInfo nextMethod in methods) {object [] attribs2 = nextMethod.GetCustomAttributes (typeof (LastModifiedAttribute), false) If (attribs2! = null) {AddToMessage (nextMethod.ReturnType + "" + nextMethod.Name + "()"); foreach (Attribute nextAttrib in attribs2) WriteAttributeInfo (nextAttrib) } private static void WriteAttributeInfo (Attribute attrib) {LastModifiedAttribute lastModifiedAttrib = attrib as LastModifiedAttribute; if (lastModifiedAttrib = = null) return; / / check that date is in range DateTime modifiedDate = lastModifiedAttrib.DateModified If (modifiedDate < backDateTo) return; AddToMessage ("MODIFIED:" + modifiedDate.ToLongDateString () + ":"); AddToMessage ("" + lastModifiedAttrib.Changes) If (lastModifiedAttrib.Issues! = null) AddToMessage ("Outstanding issues:" + lastModifiedAttrib.Issues);} private static void AddToMessage (string message) {outputText.Append ("\ n" + message) This is the end of the content of "how to achieve C# reflection". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.