zoukankan      html  css  js  c++  java
  • 【转】c# 类反射简单操作

    转:http://www.jb51.net/article/25863.htm

    首先建立一个测试的类 

    复制代码代码如下:

    public class MyClass 

    public int one { set; get; } 
    public int two { set; get; } 
    public int five { set; get; } 
    public int three { set; get; } 
    public int four { set; get; } 


    然后编写反射该类的代码 

    复制代码代码如下:

    MyClass obj = new MyClass(); 
    Type t = typeof(MyClass); 
    //循环赋值 
    int i = 0; 
    foreach (var item in t.GetProperties()) 

    item.SetValue(obj, i, null); 
    i += 1; 

    //单独赋值 
    t.GetProperty("five").SetValue(obj, 11111111, null); 
    //循环获取 
    StringBuilder sb = new StringBuilder(); 
    foreach (var item in t.GetProperties()) 

    sb.Append("类型:" + item.PropertyType.FullName + " 属性名:" + item.Name + " 值:" + item.GetValue(obj, null) + "<br />"); 

    //单独取值 
    int five = Convert.ToInt32(t.GetProperty("five").GetValue(obj, null)); 
    sb.Append("单独取five的值:" + five); 
    string result = sb.ToString(); 
    Response.Write(result); 


    测试显示结果: 
    类型:System.Int32 属性名:one 值:0 
    类型:System.Int32 属性名:two 值:1 
    类型:System.Int32 属性名:five 值:11111111 
    类型:System.Int32 属性名:three 值:3 
    类型:System.Int32 属性名:four 值:4 
    单独取five的值:11111111 

  • 相关阅读:
    Pandas
    numpy常用举例
    scikit-learn 应用
    numpy基本函数
    pytong下安装安装SK-Learn
    python 在机器学习中应用函数
    决策树实战
    KNN 实战
    Java中的stream流的概念解析
    Struts2为什么要使用OGNL
  • 原文地址:https://www.cnblogs.com/wdw31210/p/4088998.html
Copyright © 2011-2022 走看看