非静态类
1.定义一个非静态类. 静态属性可通过Static|Const定义
public class GlobalModel
{
public string Error1 { get; set; } = "A1";
public string Error2 = "D1";
/// <summary>
/// 读取Model.Key,不需要实例化对象,只读
/// </summary>
public const string Error3 = "E1";
/// <summary>
/// 只读
/// </summary>
public readonly string Error4 = "F1";
/// <summary>
/// Model.Key
/// </summary>
public static string Error5 { get; } = "G1";
public static string Error6 = "K";
}
读取非静态类的属性以及属性值
using System.Reflection;
........
public void CheckModelProperty()
{
GlobalModel model = new GlobalModel();
Type t = model.GetType();
var properties = t.GetProperties(); //这里读取的属性只能读取到含有{get;}访问器
//遍历判断是否存在某个属性名/某个属性Value值
foreach (System.Reflection.PropertyInfo s in properties)
{
//s.Name 属性名
if(s.Name=="")
{}
//读取属性的Value值
var value=s.GetValue(model, null);
}
//判断方式二
//读取Model中Error5的属性
var findkey=properties.Where(_ => _.Name == "Error5").FirstOrDefault();
// 读取Model中某个属性值为A1的属性
var findvalue=properties.Where(_ => _.GetValue(model, null).ToString() == "A1").FirstOrDefault();
}
静态类
1.定义一个静态类
public static class GlobalStaticModel
{
public const string Error1 = "A";
public static string Error2 = "B";
public static string Error3 { get; set; } = "C";
public static readonly string Error4 = "D";
}
2.读取静态类属性
public void CheckModelProperty()
{
var type = typeof(GlobalStaticModel);
var fields = type.GetFields(); //读取的Fields是不包含{get;}访问器的
//BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic;
// var fields = type.GetFields(flags);
foreach (FieldInfo t in fields)
{
var codevalue = t.GetRawConstantValue(); //非const修饰属性会异常
}
}