IPeople
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public interface IPeople
{
void Say();
}
}
MyAttribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class MyAttribute : Attribute
{
private string name;
public MyAttribute(string name)
{
this.Name = name;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
}
Woman
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
[MyAttribute("女人努力花钱")]
public class Woman : IPeople
{
public void Say()
{
Console.WriteLine("WomanSay");
}
}
}
Man
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
[MyAttribute("男人努力赚钱")]
public class Man : IPeople
{
public void Say()
{
Console.WriteLine("Man Say");
}
}
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using ClassLibrary1;
using System.Runtime.Remoting;
namespace ConsoleApplication46
{
class Program
{
static void Main(string[] args)
{
ObjectHandle p = Activator.CreateInstance("ClassLibrary1", string.Format("ClassLibrary1.{0}", "Man"));
object ps = p.Unwrap();
foreach (var item in ps.GetType().GetInterfaces())
{
Console.WriteLine(item.Name);
}
foreach (object item in ps.GetType().GetCustomAttributes(false))
{
MyAttribute my = item as MyAttribute;
if (my != null)
{
Console.WriteLine(my.Name);
}
}
IPeople pe = (IPeople)ps;
pe.Say();
Console.ReadKey();
}
}
}
运行结果:
项目结构: