请问关于c的具体应用场景有哪些?

2026-04-28 02:341阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计442个文字,预计阅读时间需要2分钟。

请问关于c的具体应用场景有哪些?

原创新品,引领潮流,品质卓越,体验非凡。


C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

命名空间:System.Reflection
程序集:mscorlib(在 mscorlib.dll 中)


C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

总结:
对应某个类的实例化的对象tc, 遍历获取所有属性(子成员)的方法(采用反射):

Type t = tc.GetType();//获得该类的Type //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了 foreach (PropertyInfo pi in t.GetProperties()) { object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值 string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作 //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数 if(value1.GetType() == typeof(int)) { //进行你想要的操作 } } 注意: 必须要设置了get 和set方法的属性,反射才能获得该属性 public int Pid { get { return pid; } set { pid = value; } }


c# 如何通过反射 获取\设置属性值、


//定义类 public class MyClass { public int Property1 { get; set; } } static void Main() { MyClass tmp_Class = new MyClass(); tmp_Class.Property1 = 2; Type type = tmp_Class.GetType(); //获取类型 System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性 int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值 Console.WriteLine(value_Old); propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值 int value_New = (int)propertyInfo.GetValue(tmp_Class, null); Console.WriteLine(value_New);}




请问关于c的具体应用场景有哪些?




本文共计442个文字,预计阅读时间需要2分钟。

请问关于c的具体应用场景有哪些?

原创新品,引领潮流,品质卓越,体验非凡。


C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

命名空间:System.Reflection
程序集:mscorlib(在 mscorlib.dll 中)


C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

总结:
对应某个类的实例化的对象tc, 遍历获取所有属性(子成员)的方法(采用反射):

Type t = tc.GetType();//获得该类的Type //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了 foreach (PropertyInfo pi in t.GetProperties()) { object value1 = pi.GetValue(tc, null));//用pi.GetValue获得值 string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作 //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数 if(value1.GetType() == typeof(int)) { //进行你想要的操作 } } 注意: 必须要设置了get 和set方法的属性,反射才能获得该属性 public int Pid { get { return pid; } set { pid = value; } }


c# 如何通过反射 获取\设置属性值、


//定义类 public class MyClass { public int Property1 { get; set; } } static void Main() { MyClass tmp_Class = new MyClass(); tmp_Class.Property1 = 2; Type type = tmp_Class.GetType(); //获取类型 System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性 int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值 Console.WriteLine(value_Old); propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值 int value_New = (int)propertyInfo.GetValue(tmp_Class, null); Console.WriteLine(value_New);}




请问关于c的具体应用场景有哪些?