रिफ्लेक्शन का उपयोग करके वर्तमान टाइप का विशिष्ट फील्ड प्राप्त करने के लिए Type.GetField() मेथड का उपयोग करें।
सिंटैक्स
public FieldInfo GetField(string name);
public FieldInfo GetField(string name, BindingFlags bindingAttr);
उदाहरण 1: पब्लिक फील्ड प्राप्त करना
using System;
using System.Reflection;
public class Demo {
public static void Main() {
Type type = typeof(Subject);
try {
FieldInfo fieldInfo = type.GetField("SubName");
Console.WriteLine("FieldInfo = {0}", fieldInfo);
}
catch (ArgumentNullException e) {
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
public class Subject {
public string SubName = "Science";
}
आउटपुट
FieldInfo = System.String SubName
उदाहरण 2: नल नाम (एक्सेप्शन)
using System;
using System.Reflection;
public class Demo {
public static void Main() {
Type type = typeof(Subject);
try {
FieldInfo fieldInfo = type.GetField(null);
Console.WriteLine("FieldInfo = {0}", fieldInfo);
}
catch (ArgumentNullException e) {
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
public class Subject {
public string SubName = "Science";
}
आउटपुट
System.ArgumentNullException
BindingFlags के साथ नॉन-पब्लिक फील्ड्स
using System;
using System.Reflection;
public class Subject {
public string PublicField = "Public";
private string PrivateField = "Private";
protected string ProtectedField = "Protected";
internal string InternalField = "Internal";
}
public class Demo {
public static void Main() {
Type type = typeof(Subject);
// पब्लिक (डिफ़ॉल्ट)
var pub = type.GetField("PublicField");
Console.WriteLine("Public: " + pub);
// नॉन-पब्लिक
var priv = type.GetField("PrivateField", BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("Private: " + priv);
var prot = type.GetField("ProtectedField", BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("Protected: " + prot);
// मौजूद नहीं
var missing = type.GetField("Missing");
Console.WriteLine("Missing: " + missing); // null
}
}
आउटपुट
Public: System.String PublicField
Private: System.String PrivateField
Protected: System.String ProtectedField
Missing:
FieldInfo मुख्य गुण
Name- फील्ड नामFieldType- फील्ड का टाइपIsPublic,IsPrivate,IsStatic,IsInitOnly(readonly),IsLiteral(const)Attributes- फील्ड एट्रिब्यूट्स
फील्ड वैल्यू प्राप्त/सेट करना
Subject subject = new Subject();
FieldInfo field = typeof(Subject).GetField("SubName");
// वैल्यू प्राप्त करें
string value = (string)field.GetValue(subject);
Console.WriteLine(value); // Science
// वैल्यू सेट करें
field.SetValue(subject, "Math");
Console.WriteLine(subject.SubName); // Math
// स्टेटिक फील्ड के लिए null पास करें
field.SetValue(null, "StaticValue");
GetField vs GetFields
| मेथड | रिटर्न | उपयोग |
|---|---|---|
GetField(name) | FieldInfo (सिंगल) | नाम से विशिष्ट फील्ड |
GetFields() | FieldInfo[] | सभी फील्ड्स (BindingFlags के साथ) |