zoukankan      html  css  js  c++  java
  • C#通过属性名称获取(读取)属性值的方法 z

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace PropertyNameGetPropertyValueDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                Person ps = new Person();
                ps.Name = "CTZ";
                ps.Age = 21;
    
                Demo dm = new Demo();
                dm.Str = "String";
                dm.I = 1;
    
                Console.WriteLine(ps.GetValue("Name"));
                Console.WriteLine(ps.GetValue("Age"));
                Console.WriteLine(dm.GetValue("Str"));
                Console.WriteLine(dm.GetValue("I"));
            }
        }
    
        abstract class AbstractGetValue
        {
            public object GetValue(string propertyName)
            {
                return this.GetType().GetProperty(propertyName).GetValue(this, null);
            }
        }
    
        class Person : AbstractGetValue  
        {
            public string Name
            { get; set; }
    
            public int Age
            { get; set; }
        }
    
        class Demo : AbstractGetValue
        {
            public string Str
            { get; set; }
    
            public int I
            { get; set; }
        }
    }
    

     简化版

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GetValue
    {
        class Program
        {
            static void Main(string[] args)
            {
                Person ps = new Person();
                ps.Name = "CTZ";
                ps.Age = 21;
    
                Console.WriteLine(ps.GetValue("Name"));
                Console.WriteLine(ps.GetValue("Age"));
            }
        }
    
        class Person
        {
            public string Name
            { get; set; }
    
            public int Age
            { get; set; }
    
            public object GetValue(string propertyName)
            {
                return this.GetType().GetProperty(propertyName).GetValue(this, null);
            }
        }
    }
    

     实质语句只有一句:

    this.GetType().GetProperty(propertyName).GetValue(this, null);
  • 相关阅读:
    考在职还是全日制?
    ARP欺骗病毒攻击
    AutoCAD2006安装错误之解决
    WINCE下创建多个文件分区
    在WINCE5.0中应用CMD(比如运行PING命令)
    WinCE 应用程序开机自动方法
    Wince 添加中文字库
    WinCE内核裁减(中文字体)及字库和内核的分离(转)
    WINCE基于CH7024实现TV OUT (VGA)功能
    WINCE6.0 中文支持
  • 原文地址:https://www.cnblogs.com/zeroone/p/6160246.html
Copyright © 2011-2022 走看看