zoukankan      html  css  js  c++  java
  • C#之反射动态获取类中成员

    初始接触反射概念,往下看。

    先建一个类User

    代码
    namespace ClassLibrary1
    {
    public class User
    {
    private int userid = 1;
    /// <summary>
    ///
    /// </summary>
    public int Userid
    {
    get { return userid; }
    set { userid = value; }
    }



    private string userName = "jghg";
    /// <summary>
    ///
    /// </summary>
    public string UserName
    {
    get { return userName; }
    set { userName = value; }
    }
    private string address = "ghjghj";
    /// <summary>
    ///
    /// </summary>
    public string Address
    {
    get { return address; }
    set { address = value; }
    }
    private string email = "jhgjhg";
    /// <summary>
    ///
    /// </summary>
    public string Email
    {
    get { return email; }
    set { email = value; }
    }
    private string phone = "ghjgjg";
    /// <summary>
    ///
    /// </summary>
    public string Phone
    {
    get { return phone; }
    set { phone = value; }
    }
    }
    }
    接着在主程序中获取类的属性,看代码

    代码
    namespace ConsoleApplication2
    {
    class Program
    {

    static void Main(string[] args)
    {

    Type type
    = typeof(ClassLibrary1.User);
    object obj = Activator.CreateInstance(type);

    PropertyInfo[] props
    = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo p in props)
    {
    Console.WriteLine(p.Name);

    }
    Console.ReadLine();
    }
    }
    }
    分析:

    Type type = typeof(ClassLibrary1.User); //把类转换成Type类型

    PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); //获取类中属性

    foreach (PropertyInfo p in props)  //遍历
    {
    Console.WriteLine(p.Name);

      }

  • 相关阅读:
    Evaluate Reverse Polish Notation(逆波兰表达式)
    PostreSQL linux添加psql 命令
    C#用文件流读取cvs内容并返回DataTable,并把第一行设为列名
    鹅鹅鹅饿饿
    编译器和解释器
    delphi之多线程编程
    Arduino 板子 COM 接口找不到设备
    JS事件冒泡
    vi编辑器的使用(2)
    vi编辑器的使用(1)
  • 原文地址:https://www.cnblogs.com/JinvidLiang/p/1871733.html
Copyright © 2011-2022 走看看