获取当前类型为C#的特定字段
要获取C#中当前类型的特定字段,代码如下-
示例
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
示例
让我们看另一个例子-
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
以上是 获取当前类型为C#的特定字段 的全部内容, 来源链接: utcz.com/z/338315.html