码迷,mamicode.com
首页 > Windows程序 > 详细

C# 反射、使用场景

时间:2019-07-02 10:43:20      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:rsa   form   odi   control   spl   使用场景   invoke   audio   str   

创建一个 Console 控制台应用程序,

1. 创建一个 Project

public class Project
    {
        public int ID { get; set; }

        public string ProjectName { get; set; }

        public DateTime CreateTime { get; set; }

        public DateTime? UpdateTime { get; set; }

        public string GetProject(int projectId, string projectName, DateTime createTime, DateTime? updateTime)
        {
            return string.Format("From Methods:ProjectId:{0}, Project name:{1}, CreateTime:{2}, UpdateTime:{3}",
                                        projectId, projectName, createTime, updateTime);
        }
    }

 

2. 使用反射动态给类(Project )的属性设置值、获取值

static void Main(string[] args)
        {
            Project project = new Project();
            Type projectType = project.GetType();
            object projectInstance = Activator.CreateInstance(projectType);

            //FieldInfo fieldID = projectType.GetField("ID");
            //fieldID.SetValue(projectInstance, 1);

            PropertyInfo propertyID = projectType.GetProperty("ID");
            propertyID.SetValue(projectInstance, 1);
            var projectId = propertyID.GetValue(projectInstance);

            PropertyInfo propertyName = projectType.GetProperty("ProjectName");
            propertyName.SetValue(projectInstance, "ProjectName001", null);
            var name = propertyName.GetValue(projectInstance);

            PropertyInfo propertyCreateTime = projectType.GetProperty("CreateTime");
            propertyCreateTime.SetValue(projectInstance, DateTime.Now, null);
            var createTime = propertyCreateTime.GetValue(projectInstance);

            PropertyInfo propertyUpdateTime = projectType.GetProperty("UpdateTime");
            propertyUpdateTime.SetValue(projectInstance, null, null);
            var updateTime = propertyUpdateTime.GetValue(projectInstance);

            Console.WriteLine("From Property:ProjectID:{0} Project name:{1}, CreateTime:{2}, UpdateTime:{3}",
                        propertyID, name, createTime, updateTime);

            MethodInfo method = projectType.GetMethod("GetProject");
            object[] parsArray = { 2, "Project00111", DateTime.Now.AddDays(10), null };
            var result = method.Invoke(projectInstance, parsArray);
            Console.WriteLine(result);
        }

 

C# 反射、使用场景

标签:rsa   form   odi   control   spl   使用场景   invoke   audio   str   

原文地址:https://www.cnblogs.com/leco/p/11119048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!