给对象赋值的另类方法

新建一工程文件,选择控制台输出,起名为Exam1 ,在工程文件里新建类Student,代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace Exam1
{
    class Student
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string sex;

        public string Sex
        {
            get { return sex; }
            set { sex = value; }
        }     

    }
}

在Program类中编写如下代码:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;

namespace Exam1
{
    class Program
    {
        static void Main(string[] args)
        {
            Student o = Activator.CreateInstance<Student>();//创建一个Student对象
            Type t = typeof(Student);
            NameValueCollection nvData = new NameValueCollection();
            nvData.Add("Name", "lucas");
            nvData.Add("Sex", "男");
            foreach (string key in nvData.Keys)
            {
                PropertyInfo pinfo = t.GetProperty(key);
                pinfo.SetValue(o, nvData[key], null);//给属性赋值
            }
            Console.WriteLine(o.Name);
            Console.WriteLine(o.Sex);
            Console.ReadLine();
        }
    }
}

输出结果:就是对象的两个属性值。

此类是利用C#的反射,创建一个实例,并用反射找到对象的属性,给属性赋值。

反射的使用一般是需要动态创建一个对象。大家可以把大家Copy到电脑里试试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值