[Serializable] |
Fields are variables defined in the class.FieldInfo provides access to the metadata for a field within a class and provides dynamic set and get functionality for the field. The class is not loaded into memory until invoke or get is called on the object.
using System; using System.Reflection; public class FieldInfoClass { public int myField1 = 0; protected string myField2 = null; public static void Main() { FieldInfo[] myFieldInfo; Type myType = typeof(FieldInfoClass); // Get the type and fields of 'FieldInfoClass' class. myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); Console.WriteLine("\nThe fields related to " + "'FieldInfoClass' class are \n"); // Print the properties of 'FieldInfoClass' class. for(int i = 0; i < myFieldInfo.Length; i++) { Console.WriteLine("\nName : {0}", myFieldInfo[i].Name); Console.WriteLine("Declaring Type : {0}", myFieldInfo[i].DeclaringType); Console.WriteLine("IsPublic : {0}", myFieldInfo[i].IsPublic); Console.WriteLine("MemberType : {0}", myFieldInfo[i].MemberType); Console.WriteLine("FieldType : {0}", myFieldInfo[i].FieldType); Console.WriteLine("IsFamily : {0}", myFieldInfo[i].IsFamily); } } }
Attributes | Read-only Gets the attributes associated with this field. |
DeclaringType (inherited from System.Reflection.MemberInfo) |
Read-only See base class member description: System.Reflection.MemberInfo.DeclaringType Gets the class that declares this member. |
FieldHandle | Read-only Gets a RuntimeFieldHandle, which is a handle to the internal metadata representation of a field. |
FieldType | Read-only Gets the type of this field object. |
IsAssembly | Read-only Gets a value indicating whether this field has Assembly level visibility. |
IsFamily | Read-only Gets a value indicating whether this field has Family level visibility. |
IsFamilyAndAssembly | Read-only Gets a value indicating whether this field has FamilyAndAssembly level visibility. |
IsFamilyOrAssembly | Read-only Gets a value indicating whether this field has FamilyOrAssembly level visibility. |
IsInitOnly | Read-only Gets a value indicating whether the field can only be set in the body of the constructor. |
IsLiteral | Read-only Gets a value indicating whether the value is written at compile time and cannot be changed. |
IsNotSerialized | Read-only Gets a value indicating whether this field has the NotSerialized attribute. |
IsPinvokeImpl | Read-only Gets a value indicating whether the corresponding PinvokeImpl attribute is set in FieldAttributes. |
IsPrivate | Read-only Gets a value indicating whether the field is private. |
IsPublic | Read-only Gets a value indicating whether the field is public. |
IsSpecialName | Read-only Gets a value indicating whether the corresponding SpecialName attribute is set in the FieldAttributes enumerator. |
IsStatic | Read-only Gets a value indicating whether the field is static. |
MemberType | Read-only Overridden: Gets the Type of property reflected by this FieldInfo object. The retrieved value indicates that this member is a field. |
Name (inherited from System.Reflection.MemberInfo) |
Read-only See base class member description: System.Reflection.MemberInfo.Name Gets the name of this member. |
ReflectedType (inherited from System.Reflection.MemberInfo) |
Read-only See base class member description: System.Reflection.MemberInfo.ReflectedType Gets the class object that was used to obtain this instance of MemberInfo. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(bool inherit) See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of all of the custom attributes. |
GetCustomAttributes (inherited from System.Reflection.MemberInfo) |
Overloaded:GetCustomAttributes(Type attributeType, bool inherit) See base class member description: System.Reflection.MemberInfo.GetCustomAttributesWhen overridden in a derived class, returns an array of custom attributes identified by Type. |
GetFieldFromHandle | Gets a FieldInfo containing the value of the field reflected by this instance. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
GetValue | When overridden in a derived class, returns the value of a field supported by a given object. |
GetValueDirect | Returns the value of a field supported by a given object. |
IsDefined (inherited from System.Reflection.MemberInfo) |
See base class member description: System.Reflection.MemberInfo.IsDefined When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member. |
SetValue | Overloaded:SetValue(object obj, object value) Sets the value of the field supported by the given object. |
SetValue | Overloaded:SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) When overridden in a derived class, sets the value of the field supported by the given object. |
SetValueDirect | Sets the value of the field supported by the given object. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. Initializes a new instance of the FieldInfo class. |
Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
protected FieldInfo(); |
public abstract FieldAttributes Attributes {get;}
|
To get the Attributes property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the Attributes.
public abstract Type DeclaringType {get;}
|
interface i { int MyVar() ; }; // DeclaringType for MyVar is i. class A : i { public int MyVar() { return 0; } }; // DeclaringType for MyVar is A. class B : A { new int MyVar() { return 0; } }; // DeclaringType for MyVar is B. class C : A { }; // DeclaringType for MyVar is A.
The following example uses DeclaringType to retrieve the member names of the System.IO.BufferedStream class, along with the class in which those members are declared.
using System; using System.IO; using System.Reflection; class Mymemberinfo { public static void Main(string[] args) { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo. Type MyType =Type.GetType("System.IO.BufferedStream"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method. Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); Console.Write("{0}.", MyType.FullName); foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { Console.Write("\n" + Mymemberinfo.Name + " declaring type - " + Mymemberinfo.DeclaringType); } } }
This code produces the following output:
Reflection.MemberInfo
There are 31 members in System.IO.BufferedStream.
WriteByte declaring type - System.IO.BufferedStream
Write declaring type - System.IO.BufferedStream
ReadByte declaring type - System.IO.BufferedStream
Read declaring type - System.IO.BufferedStream
SetLength declaring type - System.IO.BufferedStream
Seek declaring type - System.IO.BufferedStream
EndWrite declaring type - System.IO.Stream
BeginWrite declaring type - System.IO.Stream
EndRead declaring type - System.IO.Stream
BeginRead declaring type - System.IO.Stream
Flush declaring type - System.IO.BufferedStream
Close declaring type - System.IO.BufferedStream
set_Position declaring type - System.IO.BufferedStream
get_Position declaring type - System.IO.BufferedStream
get_Length declaring type - System.IO.BufferedStream
get_CanWrite declaring type - System.IO.BufferedStream
get_CanSeek declaring type - System.IO.BufferedStream
get_CanRead declaring type - System.IO.BufferedStream
InitializeLifetimeService declaring type - System.MarshalByRefObject
GetHashCode declaring type - System.Object
Equals declaring type - System.Object
ToString declaring type - System.Object
GetLifetimeService declaring type - System.MarshalByRefObject
GetType declaring type - System.Object
.ctor declaring type - System.IO.BufferedStream
.ctor declaring type - System.IO.BufferedStream
CanRead declaring type - System.IO.BufferedStream
CanWrite declaring type - System.IO.BufferedStream
CanSeek declaring type - System.IO.BufferedStream
Length declaring type - System.IO.BufferedStream
Position declaring type - System.IO.BufferedStream
In the following code example, when B overrides virtual method M from A, it essentially redefines (or redeclares) this method. Therefore, B.M's MethodInfo reports the declaring type as B rather than A, even though A is where this method was originally declared.
class A { virtual public void M () {} } class B: A { override public void M () {} }
public abstract RuntimeFieldHandle FieldHandle {get;}
|
using System; using System.Reflection; public class MyClass { public string MyField = "Microsoft"; } public class FieldInfo_FieldHandle { public static void Main() { MyClass myClass =new MyClass(); // Get the type of the class 'MyClass'. Type myType = typeof(MyClass); try { // Get the field information of 'MyField' in 'MyClass'. FieldInfo myFieldInfo = myType.GetField("MyField", BindingFlags.Public | BindingFlags.Instance); // Check whether the fieldInfo object is null or not. if(myFieldInfo!=null) { // Get the handle for the field. RuntimeFieldHandle myFieldHandle=myFieldInfo.FieldHandle; DisplayFieldHandle(myFieldHandle); } else { Console.WriteLine("The 'myFieldInfo' object is null"); } } catch(Exception e) { Console.WriteLine(" Exception : {0}", e.Message); } } public static void DisplayFieldHandle(RuntimeFieldHandle myFieldHandle) { // Get the type from the handle. FieldInfo myField = FieldInfo.GetFieldFromHandle(myFieldHandle); // Display the type. Console.WriteLine("\nDisplaying the field from the handle.\n"); Console.WriteLine("The type is : '{0}' ", myField.ToString()); } }
public abstract Type FieldType {get;}
|
To get the FieldType property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the FieldType value.
//Make a field public class Myfield { private string field = "private field"; public string Field{ get{return field;} } } public class Myfieldinfo { public static int Main() { Console.WriteLine ("\nReflection.FieldInfo"); Myfield Myfield = new Myfield(); //Get the Type and FieldInfo Type MyType = Type.GetType("Myfield"); FieldInfo Myfieldinfo = MyType.GetField("field", BindingFlags.Instance|BindingFlags.NonPublic); //Get and Display the FieldType Console.Write ("\n{0}.", MyType.FullName); Console.Write ("{0} - ", Myfieldinfo.Name); Console.Write ("{0};", Myfield.Field); Console.Write ("\nFieldType = {0}", Myfieldinfo.FieldType); return 0; } }This code produces the following output:
Reflection.FieldInfo Myfield.field - private field; FieldType = System.String
public bool IsAssembly {get;}
|
The IsAssembly property is set when the FieldAttributes.Assembly attribute is set. In C#, you can declare the field as internal to set this property to limit the access of this field to this project.
//Make two fields. public class Myfielda { private string field = "A private field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldb { internal string field = "B public field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); //For the first field, get and display the name, field, and IsAssembly. Console.Write("\n{0} - ", MyTypea.FullName); Console.Write("{0};", Myfieldinfoa.GetValue(Myfielda)); Console.Write(" IsAssembly = {0}; ", Myfieldinfoa.IsAssembly ); if (Myfieldinfoa.IsAssembly) Console.Write("Field has limited accessibility"); //For the second field, get and display the name, field, and IsAssembly. Console.Write("\n{0} - ", MyTypeb.FullName); Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb)); Console.Write(" IsAssembly = {0}; ", Myfieldinfob.IsAssembly ); if (Myfieldinfob.IsAssembly) Console.Write("Field has limited accessibility"); return 0; } }This code produces the following output:
Reflection.FieldInfo Myfielda - A private field; IsAssembly = False; Myfieldb - B public field; IsAssembly = True; Field has limited accessibility
public bool IsFamily {get;}
|
To get the IsFamily property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsFamily value.
The IsFamily property is set when the FieldAttributes.Family attribute is set.
//Make two fields. using System; using System.Reflection; public class Myfielda { private string field = "A private field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldb { protected string field = "B public field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); //For the first field, get and display the Name, field, and IsFamily. Console.Write("\n{0} - ", MyTypea.FullName); Console.Write("{0} - ", Myfieldinfoa.GetValue(Myfielda)); Console.Write("\n IsFamily - {0}", Myfieldinfoa.IsFamily); Console.Write("\n FieldAttributes - {0}", Myfieldinfoa.Attributes.ToString()); //For the second field, get and Display the Name, field, and IsFamily. Console.Write("\n{0} - ", MyTypeb.FullName); Console.Write("{0} - ", Myfieldinfob.GetValue(Myfieldb)); Console.Write("\n IsFamily - {0}", Myfieldinfob.IsFamily); FieldAttributes Myfieldattributesb = Myfieldinfob.Attributes; Console.Write("\n FieldAttributes - {0}", Myfieldinfob.Attributes.ToString()); return 0; } }
This code produces the following output:
Reflection.FieldInfo Myfielda - A private field - IsFamily - False FieldAttributes - Private Myfieldb - B public field - IsFamily - True FieldAttributes - Family
public bool IsFamilyAndAssembly {get;}
|
The IsFamilyAndAssembly property is set when the FieldAttributes.FamANDAssem attribute is set.
using System; using System.Reflection; public class Fieldinfo_IsFamilyAndAssembly { protected internal string myField = "A protected internal field"; public static void Main() { Fieldinfo_IsFamilyAndAssembly myObject = new Fieldinfo_IsFamilyAndAssembly(); //Get the Type and FieldInfo. Type myType1 = typeof(Fieldinfo_IsFamilyAndAssembly); FieldInfo myFieldInfo = myType1.GetField("myField", BindingFlags.NonPublic|BindingFlags.Instance); // Display the name, field and the FamilyAndAssembly attribute for the field. Console.Write("\n Name of Class: {0}", myType1.FullName); Console.Write("\n Value of Field: {0}", myFieldInfo.GetValue(myObject)); Console.Write("\n IsFamilyAndAssembly: {0}", myFieldInfo.IsFamilyAndAssembly ); } }
public bool IsFamilyOrAssembly {get;}
|
using System; using System.Reflection; //Make two fields. public class Myfielda //Note that if the private line below is uncommented //and the protected internal line below is commented out, //this will not compile as Myfielda.field is inaccessible. { //private string field = "A private field"; protected internal string field = "A private field"; public string Field{ get{return field;} set{if(field!=value) {field=value;}} } } //Myfieldb is derived from Myfielda. //The protected internal string field allows //the IsFamilyOrAssembly flag to be set and allows //the field to be visible from a derived class. public class Myfieldb:Myfielda { new public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); //For the first field, get and display the Name, field, and //IsFamilyOrAssembly. Console.Write("\n{0} - ", MyTypea.FullName); Console.Write("{0};", Myfieldinfoa.GetValue(Myfielda)); Console.Write("\n IsFamilyOrAssembly = {0};", Myfieldinfoa.IsFamilyOrAssembly); if (Myfieldinfoa.IsFamilyOrAssembly ) Console.Write("Field has limited accessibility"); //For the second field, get and display the name and field. Console.Write("\n{0} - ", MyTypeb.FullName); Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb)); return 0; } }
This code produces the following output:
Reflection.FieldInfo Myfielda - A private field; IsFamilyOrAssembly = True; Field has limited accessibility Myfieldb - A private field;
public bool IsInitOnly {get;}
|
To get the IsInitOnly property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsInitOnly property. To access a non-public field, set the BindingFlags to NonPublic and choose either Static or InstanceBindingFlags in the GetField method.
The IsInitOnly property is set when the FieldAttributes.InitOnly attribute is set.
using System; using System.Reflection; //Make two fields, one public and one read-only. public class Myfielda { public string field = "A - public field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldb { readonly string field = "B - readonly field"; public string Field{ get{return field;} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.Public|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); //Modify the fields. //Note that Myfieldb is not modified, as it is //read-only (IsInitOnly is True). Myfielda.field = "A- modified"; //Myfieldb.field = "B- modified"; //For the first field, get and display the name, field, and IsInitOnly. Console.Write("\n{0} - {1}, IsInitOnly = {2} ", MyTypea.FullName, Myfieldinfoa.GetValue(Myfielda), Myfieldinfoa.IsInitOnly); //For the second field get and display the name, field, and IsInitOnly. Console.Write("\n{0} - {1}, IsInitOnly = {2} ", MyTypeb.FullName, Myfieldinfob.GetValue(Myfieldb), Myfieldinfob.IsInitOnly); return 0; } }
This code produces the following output:
Reflection.FieldInfo Myfielda - A- modified, IsInitOnly = False Myfieldb - B readonly field, IsInitOnly = True
public bool IsLiteral {get;}
|
public bool IsNotSerialized {get;}
|
using System; using System.Reflection; using System.Runtime.Serialization; public class MyClass { public short myShort; // The following field will not be serialized. [NonSerialized()] public int myInt; } public class Type_IsNotSerializable { public static void Main() { // Get the type of 'MyClass'. Type myType = typeof(MyClass); // Get the fields of 'MyClass'. FieldInfo[] myFields = myType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Console.WriteLine("\nDisplaying if field is serializable\n"); // Display whether the field is serializable or not. for(int i = 0; i < myFields.Length; i++) if(myFields[i].IsNotSerialized) Console.WriteLine("'{0}' field is not serializable", myFields[i]); else Console.WriteLine("'{0}' field is serializable", myFields[i]); } }
public bool IsPinvokeImpl {get;}
|
using System; using System.Reflection; public class Fieldinfo_IsPinvoke { public string myField = "A public field"; public static void Main() { Fieldinfo_IsPinvoke myObject = new Fieldinfo_IsPinvoke(); //Get the Type and FieldInfo. Type myType1 = typeof(Fieldinfo_IsPinvoke); FieldInfo myFieldInfo = myType1.GetField("myField", BindingFlags.Public|BindingFlags.Instance); // Display the name, field and the PInvokeImpl attribute for the field. Console.Write("\n Name of Class: {0} ", myType1.FullName); Console.Write("\n Value of Field: {0}", myFieldInfo.GetValue(myObject)); Console.Write("\n IsPinvokeImpl: {0} ", myFieldInfo.IsPinvokeImpl ); } }
public bool IsPrivate {get;}
|
The IsPrivate property is set when the FieldAttributes.Private attribute is set.
To get the IsPrivate property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsPrivate property. To access a non-public field, set the BindingFlags to NonPublic, and either Static or Instance in the GetField method.
using System; using System.Reflection; class MyClass { private string myField; public string[] myArray = new string[] {"New York", "New Jersey"}; MyClass() { myField = "Microsoft"; } string GetField { get { return myField; } } } class FieldInfo_IsPrivate { public static void Main() { try { // Gets the type of 'MyClass'. Type myType = typeof(MyClass); // Gets the field information of 'MyClass'. FieldInfo[] myFields = myType.GetFields(BindingFlags.NonPublic |BindingFlags.Public |BindingFlags.Instance); Console.WriteLine("\nDisplaying whether the fields of '{0}' are private or not:\n",myType); for(int i = 0; i < myFields.Length; i++) { // Check whether the field is private or not. if(myFields[i].IsPrivate) Console.WriteLine("'{0}' is a private field", myFields[i].Name); else Console.WriteLine("'{0}' is not a private field", myFields[i].Name); } } catch(Exception e) { Console.WriteLine("Exception : {0} " , e.Message); } } }
public bool IsPublic {get;}
|
The IsPublic property is set when the FieldAttributes.Public attribute is set.
To get the IsPublic property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsPublic property. If the field is other than public, it is protected and cannot be readily accessed. To access a not public field, set the BindingFlags to NonPublic, specify either BindingFlags.Instance or BindingFlags.Static, and use this for the GetField method.
using System; using System.Reflection; //Make two fields. public class Myfielda // private { private string SomeField = "private field"; public string Field{ get{return SomeField;} } } public class Myfieldb // public { public string SomeField = "public field"; public string Field{ get{return SomeField;} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("SomeField", BindingFlags.NonPublic|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("SomeField"); //Get and Display the IsPublic and IsPrivate. Console.Write("\n{0}.", MyTypea.FullName); Console.Write("{0} - ", Myfieldinfoa.Name); Console.Write("{0};", Myfielda.Field); Console.Write("\n IsPublic = {0}; ",Myfieldinfoa.IsPublic); Console.Write("\n IsPrivate = {0}; ",Myfieldinfoa.IsPrivate); Console.Write("\n{0}.", MyTypeb.FullName); Console.Write("{0} - ", Myfieldinfob.Name); Console.Write("{0};", Myfieldb.Field); Console.Write("\n IsPublic = {0}; ", Myfieldinfob.IsPublic); Console.Write("\n IsPrivate = {0}; ",Myfieldinfob.IsPrivate); return 0; } }This code produces the following output:
Reflection.FieldInfo
Myfielda.SomeField - private field;
IsPublic = False;
IsPrivate = True;
Myfieldb.SomeField - public field;
IsPublic = True;
IsPrivate = False;
public bool IsSpecialName {get;}
|
using System; using System.Reflection; using System.ComponentModel.Design; class FieldInfo_IsSpecialName { public static void Main() { try { // Get the type handle of the 'ViewTechnology' class. Type myType = typeof(ViewTechnology); // Get the fields of the class 'ViewTechnology'. FieldInfo[] myField = myType.GetFields(); Console.WriteLine("\nDisplaying fields that have 'SpecialName' attributes\n"); for(int i = 0; i < myField.Length; i++) { // Check whether each field is a special name or not. if(myField[i].IsSpecialName) { Console.WriteLine("The field '{0}' has SpecialName attribute", myField[i].Name); } } } catch(Exception e) { Console.WriteLine("Exception : {0} " , e.Message); } } }
public bool IsStatic {get;}
|
The IsStatic property is set when the FieldAttributes.Static attribute is set.
To get the IsStatic property, first get the class Type. From the Type, get the FieldInfo. From the FieldInfo, get the IsStatic property. To access a non-public field, set the BindingFlags to NonPublic in the GetField method and set the accessibility to Instance or Static.
using System; using System.Reflection; //Make two fields. public class Myfielda { private string field = "A private field"; public string Field{ get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldb { static string field = "B static field"; public string Field { get{return field;} set{if(field!=value){field=value;}} } } public class Myfieldinfo { public static int Main() { Console.WriteLine("\nReflection.FieldInfo"); Myfielda Myfielda = new Myfielda(); Myfieldb Myfieldb = new Myfieldb(); //Get the Type and FieldInfo. Type MyTypea = Type.GetType("Myfielda"); FieldInfo Myfieldinfoa = MyTypea.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); Type MyTypeb = Type.GetType("Myfieldb"); FieldInfo Myfieldinfob = MyTypeb.GetField("field", BindingFlags.NonPublic|BindingFlags.Static); //For the first field, get and display the name, field, and IsStatic. Console.Write("\n{0} - ", MyTypea.FullName); Console.Write("{0}; ", Myfieldinfoa.GetValue(Myfielda)); Console.Write("IsStatic - {0}", Myfieldinfoa.IsStatic); //For the second field get and display the name, field, and IsStatic. Console.Write("\n{0} - ", MyTypeb.FullName); Console.Write("{0}; ", Myfieldinfob.GetValue(Myfieldb)); Console.Write("IsStatic - {0}", Myfieldinfob.IsStatic); return 0; } }This code produces the following output:
Reflection.FieldInfo
Myfielda - A private field; IsStatic - False
Myfieldb - B static field; IsStatic - True
public override MemberTypes MemberType {get;}
|
using System; using System.Reflection; //Make a field public class Myfield { private string field = "a private field"; public string Field{ get{return field;} } } public class Myfieldinfo { public static int Main() { Console.WriteLine ("\nReflection.FieldInfo"); Myfield Myfield = new Myfield(); //Get the Type and FieldInfo Type MyType = Type.GetType("Myfield"); FieldInfo Myfieldinfo = MyType.GetField("field", BindingFlags.NonPublic|BindingFlags.Instance); //Get and Display the MemberType Console.Write ("\n{0}.", MyType.FullName); Console.Write ("{0} - ", Myfieldinfo.Name); Console.Write ("{0};", Myfield.Field); MemberTypes Mymembertypes = Myfieldinfo.MemberType; Console.Write(" MemberType is a {0}", Mymembertypes.ToString()); return 0; } }This code produces the following output:
Reflection.FieldInfo
Myfield.field - a private field; MemberType is a Field
public abstract string Name {get;}
|
To get the Name property, get the class Type. From the Type, get the MemberInfo array. From a MemberInfo element of the array, obtain the Name property.
using System; using System.Reflection; class Mymemberinfo { public static int Main() { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo. Type MyType = Type.GetType("System.Empty"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method. Console.Write("\nThere are {0} members in ", Mymemberinfoarray.GetLength(0)); Console.Write("{0}.", MyType.FullName); foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { Console.Write("\n" + Mymemberinfo.Name + " declaring type - " + Mymemberinfo.DeclaringType); } return 0; } } /* This code produces the following output: Reflection.MemberInfo There are 6 members in System.Empty. Value declaring type - System.Empty GetObjectData declaring type - System.Empty GetHashCode declaring type - System.Object Equals declaring type - System.Object ToString declaring type - System.Empty GetType declaring type - System.Object */
public abstract Type ReflectedType {get;}
|
In order to obtain a MethodInfo object:
using System; using System.IO; using System.Reflection; class Mymemberinfo { public static void Main(string[] args) { Console.WriteLine ("\nReflection.MemberInfo"); //Get the Type and MemberInfo Type MyType =Type.GetType("System.IO.BufferedStream"); MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); //Get and display the DeclaringType method Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); Console.Write("{0}.", MyType.FullName); foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { Console.Write("\n" + Mymemberinfo.Name + " reflected type - " + Mymemberinfo.ReflectedType); } } }This code produces the following output:
Reflection.MemberInfo
There are 31 members in System.IO.BufferedStream.
WriteByte reflected type - System.IO.BufferedStream
~FieldInfo(); |
inherit
using System; using System.Reflection; // Define a custom attribute with one named parameter. [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { private string myName; public MyAttribute(string name) { myName = name; } public string Name { get { return myName; } } } // Define a class which has the custom attribute associated with one of its members. public class MyClass1 { [MyAttribute("This is an example attribute")] public void MyMethod(int i) { return; } } public class MemberInfo_GetCustomAttributes { public static void Main() { try { // Get the type of the class 'MyClass1'. Type myType = typeof(MyClass1); // Get the members associated with the class 'MyClass1'. MemberInfo[] myMembers = myType.GetMembers(); // Display the attributes for each of the members of the class 'MyClass1'. for(int i = 0; i < myMembers.Length; i++) { Object[] myAttributes = myMembers[i].GetCustomAttributes(false); if(myAttributes.Length > 0) { Console.WriteLine("\nThe attributes for the member {0} are : \n", myMembers[i]); for(int j = 0; j < myAttributes.Length; j++) Console.WriteLine("The type of the attribute is : {0}", myAttributes[j]); } } } catch(Exception e) { Console.WriteLine("Exception Caught! "+e.Message); } } }
attributeType
inherit
Exception Type | Condition |
---|---|
TypeLoadException | If the custom attribute type can not be loaded. |
public static FieldInfo GetFieldFromHandle( |
handle
using System; using System.Reflection; public class FieldInfo_GetFieldFromHandle { public string x; public char y; public float a; public int b; public static void Main() { // Get the type of 'FieldInfo_GetFieldFromHandle' class. Type myType = typeof(FieldInfo_GetFieldFromHandle); // Get the fields of 'FieldInfo_GetFieldFromHandle' class. FieldInfo [] myFieldInfoArray = myType.GetFields(); Console.WriteLine("\nThe field information of the declared" + " fields x, y, a, b:\n"); RuntimeFieldHandle myRuntimeFieldHandle; for(int i = 0; i < myFieldInfoArray.Length; i++) { // Get the RuntimeFieldHandle of the 'myFieldInfoArray'. myRuntimeFieldHandle = myFieldInfoArray[i].FieldHandle; // Call the 'GetFieldFromHandle' method. FieldInfo myFieldInfo = FieldInfo.GetFieldFromHandle(myRuntimeFieldHandle); // Print the Field information of 'myFieldInfo'. Console.WriteLine("{0}", myFieldInfo); } } }
public virtual int GetHashCode(); |
public Type GetType(); |
obj
Exception Type | Condition |
---|---|
TargetException | The field is non-static and obj is null. |
NotSupportedException | A field is marked literal, but the field does not have one of the accepted literal types. |
FieldAccessException | The caller does not have permission to access this field. |
ArgumentException | The method is neither declared nor inherited by the class of obj. |
using System; using System.Reflection; public class MyClass { public string myFieldA; public string myFieldB; public MyClass() { myFieldA = "A public field"; myFieldB = "Another public field"; } } public class FieldInfo_GetValue { public static void Main() { MyClass myInstance = new MyClass(); // Get the type of the class MyClass. Type myType = typeof(MyClass); try { // Get the FieldInfo of the class MyClass. FieldInfo[] myFields = myType.GetFields(BindingFlags.Public | BindingFlags.Instance); // Display the values of the fields to the console. Console.WriteLine("\nDisplaying the values of the fields of '{0}' class\n", myType); for(int i = 0; i < myFields.Length; i++) { Console.WriteLine("The value of the field '{0}' is : {1}", myFields[i].Name, myFields[i].GetValue(myInstance)); } } catch(FieldAccessException e) { Console.WriteLine("FieldAccessException : {0}", e.Message); } catch(TargetException e) { Console.WriteLine("TargetException : {0}", e.Message); } catch(ExecutionEngineException e) { Console.WriteLine("ExecutionEngineException : {0}", e.Message); } catch(MemberAccessException e) { Console.WriteLine("MemberAccessException : {0}", e.Message); } catch(Exception e) { Console.WriteLine("Exception : {0}", e.Message); } } }
[CLSCompliant(false)] |
obj
Exception Type | Condition |
---|---|
NotSupportedException | The caller requires the CLS alternative, but called this method instead. |
attributeType
inherit
using System; using System.Reflection; // Define a custom attribute with one named parameter. [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { private string myName; public MyAttribute(string name) { myName = name; } public string Name { get { return myName; } } } // Define a class which has the custom attribute associated with one of its members. public class MyClass1 { [MyAttribute("This is an example attribute")] public void MyMethod(int i) { return; } } public class MemberInfo_GetCustomAttributes_IsDefined { public static void Main() { try { // Get the type of the class 'MyClass1'. Type myType = typeof(MyClass1); // Get the members associated with the class 'MyClass1'. MemberInfo[] myMembers = myType.GetMembers(); // Display the attributes for each of the members of the class 'MyClass1'. for(int i = 0; i < myMembers.Length; i++) { // Display the attribute if it is of type 'MyAttribute'. if(myMembers[i].IsDefined(typeof(MyAttribute), false)) { Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false); Console.WriteLine("\nThe attributes of type 'MyAttribute' for the member {0} are : \n", myMembers[i]); for(int j = 0; j < myAttributes.Length; j++) // Display the value associated with the attribute. Console.WriteLine("The value of the attribute is : \"{0}\"", ((MyAttribute)myAttributes[j]).Name); } } } catch(Exception e) { Console.WriteLine("Exception Caught! "+e.Message); } } }
protected object MemberwiseClone(); |
obj
value
Exception Type | Condition |
---|---|
FieldAccessException | The caller does not have permission to access this field. |
TargetException | The obj parameter is null and the field is an instance field. |
ArgumentException | The field does not exist on the object. -or- The value parameter cannot be converted and stored in the field. |
using System; using System.Reflection; using System.Globalization; public class MyClass { private string myString; public MyClass() { myString = "Old value"; } string GetField { get { return myString; } } } public class FieldInfo_SetValue { public static void Main() { try { MyClass myObject = new MyClass(); Type myType = Type.GetType("MyClass"); FieldInfo myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance); // Display string before applying 'Set Value' on the field. Console.WriteLine( "\nField value of 'myString': {0}", myFieldInfo.GetValue( myObject ) ); // Display 'SetValue' signature used to set the value of a field. Console.WriteLine( "Applying 'SetValue( Object,Object )' method"); // Change field value using 'SetValue' method. myFieldInfo.SetValue( myObject , "New value"); // Display string after applying 'Set Value' on the field. Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject ) ); // Set field value using 'SetValue' method to its old value. myFieldInfo.SetValue( myObject , "Old value" ); myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance); // Display string before applying 'SetValue' on the field. Console.Write( "\nField value of 'mystring' : {0}\n", myFieldInfo.GetValue( myObject ) ); // Display 'SetValue' signature used to set value of a field. Console.WriteLine( "Applying 'SetValue( Object,Object,BindingFlags,Binder,CultureInfo )' method"); // Change field value using 'SetValue' method. myFieldInfo.SetValue( myObject, "New value", BindingFlags.Default, null , null ); // Display string after applying 'SetValue' on the field. Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject ) ); } catch( Exception e ) { // Any exception generated is displayed. Console.WriteLine( "Exception: {0}", e.Message ); } } }
public abstract void SetValue( |
obj
value
invokeAttr
binder
culture
Exception Type | Condition |
---|---|
FieldAccessException | The caller does not have permission to access this field. |
TargetException | The obj parameter is null and the field is an instance field. |
ArgumentException | The field does not exist on the object. -or- The value parameter cannot be converted and stored in the field. |
using System; using System.Reflection; using System.Globalization; public class MyClass { private string myString; public MyClass() { myString = "Old value"; } string GetField { get { return myString; } } } public class FieldInfo_SetValue { public static void Main() { try { MyClass myObject = new MyClass(); Type myType = Type.GetType("MyClass"); FieldInfo myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance); // Display string before applying 'Set Value' on the field. Console.WriteLine( "\nField value of 'myString': {0}", myFieldInfo.GetValue( myObject ) ); // Display 'SetValue' signature used to set the value of a field. Console.WriteLine( "Applying 'SetValue( Object,Object )' method"); // Change field value using 'SetValue' method. myFieldInfo.SetValue( myObject , "New value"); // Display string after applying 'Set Value' on the field. Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject ) ); // Set field value using 'SetValue' method to its old value. myFieldInfo.SetValue( myObject , "Old value" ); myFieldInfo = myType.GetField("myString", BindingFlags.NonPublic | BindingFlags.Instance); // Display string before applying 'SetValue' on the field. Console.Write( "\nField value of 'mystring' : {0}\n", myFieldInfo.GetValue( myObject ) ); // Display 'SetValue' signature used to set value of a field. Console.WriteLine( "Applying 'SetValue( Object,Object,BindingFlags,Binder,CultureInfo )' method"); // Change field value using 'SetValue' method. myFieldInfo.SetValue( myObject, "New value", BindingFlags.Default, null , null ); // Display string after applying 'SetValue' on the field. Console.WriteLine( "Field value of 'mystring' : {0}", myFieldInfo.GetValue( myObject ) ); } catch( Exception e ) { // Any exception generated is displayed. Console.WriteLine( "Exception: {0}", e.Message ); } } }
[CLSCompliant(false)] |
obj
value
Exception Type | Condition |
---|---|
NotSupportedException | The caller requires the CLS alternative, but called this method instead. |
public virtual string ToString(); |