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);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM