(也许你可以使用DLR来完成,如果我的PostSharp解决方案是不够的?)
当然可以。您可以在实例作用域方面使用引入成员属性。你最好的选择是使用postshsrp实现一个接口,然后引用你的目标类作为该接口来公开该方法。您也可以使用Post.Cast <>()在设计时访问它。
这里有两种方法可以做到这一点。第一个是通过接口,第二个是使用存根。
方法1 - 接口
public class Program
{
static void Main(string[] args)
{
Customer c = new Customer();
var cc = Post.Cast<Customer, ISomething>(c);
cc.SomeMethod();
}
}
public interface ISomething
{
void SomeMethod();
}
[AddMethodAspect]
public class Customer
{
}
[Serializable]
[IntroduceInterface(typeof(ISomething))]
public class AddMethodAspect : InstanceLevelAspect, ISomething
{
#region ISomething Members
public void SomeMethod()
{
Console.WriteLine("Hello");
}
#endregion
}
方法2 - 存根
public class Program
{
static void Main(string[] args)
{
Customer c = new Customer();
c.SomeMethod();
}
}
[AddMethodAspect]
public class Customer
{
public void SomeMethod() { }
}
[Serializable]
public class AddMethodAspect : InstanceLevelAspect
{
[IntroduceMember(OverrideAction = MemberOverrideAction.OverrideOrFail)]
public void SomeMethod()
{
Console.WriteLine("Hello");
}
}
更多信息 以防万一有一些问题与使用Cast <>()功能,它不会做实际的演员。编译结果如下:
private static void Main(string[] args)
{
Customer c = new Customer();
ISomething cc = c;
cc.SomeMethod();
}
更新了我的答案,其中包括2个方法来引入方法。 –