using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
//1.获取类型
Type type = typeof(Person);
//2.获取属性
var propertyInfo = type.GetProperty("Name");
//3.创建实例
var instance = Activator.CreateInstance(type);
//4.设置属性值
propertyInfo?.SetValue(instance, "FXX");
//5.获取属性值
var name = propertyInfo?.GetValue(instance);
Console.WriteLine(name);
}
}
二、使用反射操作字段
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
private string _address;
}
public class Program
{
public static void Main()
{
Type type = typeof(Person);
var propertyInfo = type.GetField("_address",BindingFlags.Instance|BindingFlags.NonPublic);
var instance = Activator.CreateInstance(type);
propertyInfo?.SetValue(instance, "Forrest Hill");
var adrress = propertyInfo?.GetValue(instance);
Console.WriteLine(adrress);
}
}
三、操作程序集
public class Program
{
public static void Main()
{
//根据程序集名称加载程序集
var assembly = Assembly.Load("ConsoleApp1");
//获取程序集完整路径
string location = assembly.Location;
Console.WriteLine(location);
//获取程序集名称
string name = assembly.GetName().Name;
Console.WriteLine(name);
}
}