using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace 反射
{
class Program
{
static void Main(string[] args)
{
//枚举类型成员
//实例化新对象
//执行对象的成员
//查找类型的信息
//查找程序集的信息
//检查应用于某种类型的自定义特性
//创建和编译新程序集
#region 自定义特性
#endregion
#region WhatsNewAttributes 库程序集
#endregion
#region VectorClass 库程序集
#endregion
#region String.Type 类
//只为了存储类型的引用
//
Type t = typeof(double);
double d = 10;
Type t1 = d.GetType();
Type t2 = Type.GetType("System.Double");
//Type是许多反射功能的入口。它实现许多方法和属性,都是只读的
//Name:数据类型名
//FullName:数据类型的完全限定名(包括命名空间名)
//Namespace:在其中定义数据类型的名称命名
Console.WriteLine(t1.IsAbstract);
Console.WriteLine(t1.IsClass);
Console.WriteLine(t1.IsEnum);
Console.WriteLine(t1.IsPrimitive);
Console.WriteLine(t1.IsValueType);
//获取在其中定义该类型的程序集的引用
//Assembly contai6ningAssembly = new Assembly(t1);
#endregion
#region TypeView
Type t3 = typeof(double);
AnalyzeType(t3);
#endregion
#region Assembly 类
Assembly assembly1 = Assembly.Load("SomeAssembly");
Assembly assembly2 = Assembly.Load(@"c:\SomeAssembly");
string name = assembly1.FullName;
//可以正常操作了,像上面一样
Type[] types = assembly1.GetTypes();
//Attribute supportsAttribute = Attribute.GetCustomAttribute(assembly1, typeof(decimal));
#endregion
#region WhatsNewAttribuutes 实例
#endregion
}
static void AnalyzeType(Type t) {
Console.WriteLine("Type Name:"+t.Name);
Console.WriteLine("Type Name:" + t.FullName);
Console.WriteLine("Type Name:" + t.Namespace);
Type tBase = t.BaseType;
if (tBase != null) {
Console.WriteLine("Base Name:" + tBase.Name);
}
Type tUnderlyingSystem = t.UnderlyingSystemType;
if (tUnderlyingSystem != null) {
Console.WriteLine("tUnderlyingSystem:" + tUnderlyingSystem.Name);
}
MemberInfo[] members = t.GetMembers();
foreach (MemberInfo item in members)
{
Console.WriteLine(item.DeclaringType+"");
Console.WriteLine(item.MemberType + "");
Console.WriteLine(item.Name + "");
}
}
}
public class a {
[FieldNameAttribute("SocialSecurityNumber")]
public string SocialSecurityNumber { get; set; }
}
/// <summary>
/// 自定义特性类 有多个可以用|隔开
/// </summary>
[AttributeUsage(AttributeTargets.Property,AllowMultiple =false,Inherited =false)]
public class FieldNameAttribute : Attribute {
private string name;
public FieldNameAttribute(string name) {
this.name = name;
}
}
}
15:反射
最新推荐文章于 2024-11-07 19:52:01 发布