C# 反射、使用场景
2021-05-28 17:08
标签:rsa form odi control spl 使用场景 invoke audio str 创建一个 Console 控制台应用程序, 1. 创建一个 Project 类 2. 使用反射动态给类(Project )的属性设置值、获取值 C# 反射、使用场景 标签:rsa form odi control spl 使用场景 invoke audio str 原文地址:https://www.cnblogs.com/leco/p/11119048.htmlpublic 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);
}
}
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);
}