反射 动态激活代码
创建一个自定义特性类
namespace UseAttribute
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class UserAttribute:Attribute
{
private string comment;
public UserAttribute(string mm)
{
comment = mm;
}
public string Comment
{
set
{
comment=value;
}
get
{
return comment;
}
}
}
}
创建类 DLL
[assembly:UserAttribute("use attribute for namespace ReflectDll")]
namespace ReflectDll
{
public interface IC
{
void show();
}
[UserAttribute("use attribute for TC1 ")]
public class TC1:IC
{
public TC1(string t)
{
m_show=t;
}
public string Text
{
get{
return m_show;
}
}
public void show()
{
Console.WriteLine(m_show);
}
private string m_show = "this is init for TC1";
}
public class TC2
{
public TC2()
{
}
public void show()
{
Console.WriteLine("This is TC2");
}
}
}
动态激活代码
static void Main(string[] args)
{
Assembly asm = Assembly.Load("ReflectDll");
//调用一个方法
Type classtype = asm.GetType("ReflectDll.TC1");
Type[] classtypes = asm.GetTypes();
foreach(Type t in classtypes)
{
Console.WriteLine(t.Name);
}
object reflectobj = Activator.CreateInstance(classtype,"This is TC1");
MethodInfo meth = classtype.GetMethod("show");
meth.Invoke(reflectobj, null);
//调用一个属性
PropertyInfo prop = classtype.GetProperty("Text");
MethodInfo prop_meth= prop.GetGetMethod();
Console.WriteLine(prop_meth.Invoke(reflectobj, null));
//调用一个特性
Attribute attri = Attribute.GetCustomAttribute(asm, typeof(UserAttribute));
Console.WriteLine(attri.ToString());
Attribute[] attri2 = Attribute.GetCustomAttributes(classtype);
foreach (Attribute at in attri2)
{
UserAttribute uat = at as UserAttribute;
Console.WriteLine(uat.Comment);
}
}
浙公网安备 33010602011771号