Net 读取静态类与非静态类的属性

本文介绍了如何在C#中读取非静态类和静态类的属性。对于非静态类,讲解了定义及通过Static或Const声明静态属性的方法,并阐述了获取属性值的步骤。对于静态类,详细说明了定义过程以及读取静态类属性的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非静态类

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修饰属性会异常
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值