反射基本功能:
① 在程序运行过程中读取和修改对象中的参数(属性、方法、字段等)
② 通过反射对程序进行更新,不需要改动原程序
反射作用1练习:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fanshe
{
class student
{
public int age;
public string name;
public int ID { get; set; }
public student(string Name)
{
this.name = Name;
}
public void show()
{
Console.WriteLine("this is shown");
}
public void show2(string Age)
{
Console.WriteLine($"this is {Age}");
}
}
class Program
{
static void Main(string[] args)
{
object obj = new student("jerry");
Type x = obj.GetType();
//反射作用:① 通过反射遍历成员,并调用成员
//type的常用属性:Name;full name;namespace
Console.WriteLine(x.Name); //student
Console.WriteLine(x.FullName); //fanshe.student
Console.WriteLine(x.Namespace); //fanshe
foreach (var item in x.GetFields())
{
//显示出当前obj对象中的字段
Console.WriteLine(item.Name); //age name
}
//输出obj对象中age字段数值
x.GetField(name: "age").SetValue(obj, 30);
int y = (int)x.GetField(name: "age").GetValue(obj);
Console.WriteLine(y);
Console.WriteLine("//");
//输出对象属性
foreach (var item in x.GetProperties())
{
Console.WriteLine(item.Name); //ID
Console.WriteLine(item.PropertyType.Name); //Int32
Console.WriteLine(item.PropertyType.FullName); //system.Int32
}
var id = x.GetProperty(name: "ID");
id.SetValue(obj,100);
Console.WriteLine(id.GetValue(obj)); //100
Console.WriteLine("/");
//输出obj对象中的方法
foreach (var item in x.GetMethods())
{
Console.WriteLine(item.Name);
}
x.GetMethod(name: "show").Invoke(obj,null);
x.GetMethod(name: "show2").Invoke(obj,new object[] {"jerry"});
Console.ReadKey();
}
}
}
作用2练习:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Environment.CurrentDirectory);
Assembly ss = Assembly.LoadFile(Environment.CurrentDirectory+ @"\libs\studentmanager.dll");
foreach (var item in ss.GetTypes())
{
Console.WriteLine(item.Name);
//使用is属性对参数进行过滤,找到想找的内容
Console.WriteLine(item.IsClass);
Console.WriteLine(item.IsAbstract);
}
Console.WriteLine("///");
var t = ss.GetTypes().First(x=>x.IsAbstract==false && x.IsClass ==true);
Console.WriteLine(t.Name);
//此时是没有对象的,需要重新创建对象
object obj = ss.CreateInstance(t.FullName);
t.GetProperty(name: "Age").SetValue(obj,30);
t.GetProperty(name: "Name").SetValue(obj,"jerry");
int kl = (int)t.GetProperty(name: "Age").GetValue(obj);
Console.WriteLine(kl);
t.GetMethod(name: "show").Invoke(obj,new object[] { });
//t.GetProperty(name: "Age").SetValue(obj,30);
//t.GetProperty(name: "Name").SetValue(obj,"jerry");
Console.ReadKey();
}
}
}