c#反射相关操作
作者:互联网
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//通过对象
PersonDomain person = new PersonDomain(111,"张三");
Type type1 = person.GetType();
//属性
PropertyInfo[] propertyInfolist = type1.GetProperties();
//具体属性
PropertyInfo des = type1.GetProperty("Id");
//属性值
object value = des.GetValue(person,null);
///构造
ConstructorInfo[] constructorInfolist=type1.GetConstructors();
int i=111;
Type ty1=i.GetType();
string name="string";
Type ty2=name.GetType();
Type[] types = { ty1, ty2 };
//有参构造
ConstructorInfo constructorInfo = type1.GetConstructor(types);
PersonDomain personNew = (PersonDomain)constructorInfolist[0].Invoke(new Object[0]);
Object[] obj = { 111,"张三"};
PersonDomain personNew2 = (PersonDomain)constructorInfolist[1].Invoke(obj);
//公共字段//值FieldInfo.GetValue(person);
FieldInfo FieldInfo = type1.GetField("gg");
//方法
MethodInfo[] MethodInfoList = type1.GetMethods();
MethodInfo fuc1 = type1.GetMethod("fuc1");
Type[] typefuc = { };
MethodInfo fuc2 = type1.GetMethod("fuc2", typefuc);
Type[] typeFuc22 = { ty2 };
MethodInfo fuc22 = type1.GetMethod("fuc2", typeFuc22);
//方法fuc1
fuc1.Invoke(person, new Object[0]);
//方法fuc2
fuc2.Invoke(person, new Object[0]);
//方法fuc22有参数
Object[] objfuc2 = { "张三" };
string result = fuc22.Invoke(person, objfuc2).ToString();
}
// <summary>
/// 模型赋值
/// </summary>
/// <param name="target">目标</param>
/// <param name="source">数据源</param>
public static void CopyModel(object target, object source)
{
Type type1 = target.GetType();
Type type2 = source.GetType();
foreach (var mi in type2.GetProperties())
{
var des = type1.GetProperty(mi.Name);
if (des != null)
{
try
{
des.SetValue(target, mi.GetValue(source, null), null);
}
catch
{ }
}
}
}
private void button2_Click(object sender, EventArgs e)
{
//通过类型
Type domain = Type.GetType("WindowsFormsApplication5.PersonDomain");
//得到对象
Type ty1 = Type.GetType("System.Int32");
Type ty2 = Type.GetType("System.String");
Type[] types = { ty1, ty2 };
//有参构造
ConstructorInfo constructorInfo = domain.GetConstructor(types);
//构造参数
Object[] obj = { 111, "张三" };
PersonDomain domainNew = (PersonDomain)constructorInfo.Invoke(obj);
string name = domainNew.name;
//改变name的值 name+"New"
PropertyInfo propertyInfo=domain.GetProperty("name");
propertyInfo.SetValue(domainNew, propertyInfo.GetValue(domainNew,null)+"New",null);
string nameNew = domainNew.name;
}
----------------------------------------
public class PersonDomain
{
public PersonDomain() { }
public PersonDomain(int id, string name) { this.Id = id; this.name = name; }
public int Id { get;set;}
public string name { get; set; }
public string gg="gg";
public void fuc1()
{
}
public void fuc2()
{
}
public string fuc2(string str)
{
return str;
}
}
}
标签:反射,name,c#,type1,PersonDomain,操作,Type,public,string 来源: https://blog.csdn.net/qq_41515170/article/details/101453560