您的位置:首页 > 其它

.Net实战之反射相关类之间的人体经络关系

2016-09-12 20:07 351 查看
--1.类的部分组成成员



--2.巧记成员之间的关系



[MyTable("T_UserInfo")]
public class UserInfo : Person, UserService
{

private int _age2;
private int _age;
[DisplayName("年龄")]
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
[DisplayName("姓名")]
public string Name { get; set; }
public void ShowUserInfo()
{
Console.WriteLine(string.Format("name:{0},age:{1}", Name, _age));
}

protected void ShowName()
{
Console.WriteLine("showName:" + Name);
}
}


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class MyTableAttribute : Attribute
{
private string _tableName;
public MyTableAttribute(string name)
{
_tableName = name;
}
public string Name { get { return _tableName; } }
}


--3.程序集

// 加载程序集(大脑)
//获取当前运行目录下的指定程序集名称
Assembly ass = Assembly.Load("ReflectionDemo");
//Assembly.LoadFile(),Assembly.LoadFrom()加载指定文件的程序集


--4.类型

// 加载中枢神经的 所有经络

//获取该程序集下的所有类型
Type[] types = ass.GetTypes();

//根据类的全名称(命门空间.类名)获取类的信息
Type type1 = ass.GetType("ReflectionDemo.person");

//忽略大小写或找不到该类型抛出异常
//Type type2 = ass.GetType("ReflectionDemo.person2", throwOnError: true, ignoreCase: true);

//获取程序集中公共类型
Type[] publicTypes = ass.GetExportedTypes();

//获取类的类型
Type classUserType = typeof(UserInfo);

//获取实例的类型
UserInfo ui = new UserInfo();
Type instanceType = ui.GetType();

//获取类型的名称
Console.WriteLine(string.Format("typeFullName:{0},typeName:{1}", instanceType.FullName, instanceType.Name));

//是否继承自某个类
Console.WriteLine("是否继承自某个类-----" + typeof(UserInfo).IsSubclassOf(typeof(Person)));

//是否实现了某个接口(接口的实现类型 是否是 指定的类型)
Console.WriteLine("是否实现了某个接口-----" + typeof(UserService).IsAssignableFrom(typeof(UserInfo)));

//是否是public的类型
Console.WriteLine("是否是public的类型-----" + classUserType.IsPublic);


--5.字段、属性、方法、特性

//获取字段 BindingFlags位标记 获取字段不同的方式
//t.GetField();t.GetFields()
FieldInfo fiAge = t.GetField("_age",
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
//获取属性 类似Field
t.GetProperties();
PropertyInfo pi = t.GetProperty("");
//pi.CanRead;//能读
//pi.CanWrite;//能写
//获取方法
MethodInfo[] methods = t.GetMethods();
MethodInfo method = t.GetMethod("ShowUserInfo");
//获取特性
MyTableAttribute tabAttr = t.GetCustomAttribute(typeof(MyTableAttribute)) as MyTableAttribute;
if (tabAttr != null)
{
Console.WriteLine("select * from " + tabAttr.Name);
}




下一篇,反射的数据操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: