C# 反射、使用场景

创建一个 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);
        }

 

posted @ 2019-07-02 10:37  leco_lin  阅读(2668)  评论(0编辑  收藏  举报