c# - Is it possible to add methods to classes with PostSharp? If yes, is it possible to then reference those methods from other classes? -
let's have class abc
:
class abc { }
and i'd externally add method m()
it. guess it's possible this, although not sure how. assuming possible that, let's abc have, on, m()
method.
now, imagine have other class def
:
class def { public void x(abc abc) { abc.m(); } }
would code run postsharp? more distracted reader, problem in standard c# class program, our compiler might not know abc
class has m()
method.
my gut feeling wouldn't work postsharp. mistaken?
(maybe can use dlr accomplish if postsharp solutions aren't sufficient?)
yes can. use introducemember attribute in instance scoped aspect. best bet implement interface using postshsrp reference target class interface expose method. can use post.cast<>() access @ design time.
here 2 methods this. first via interface, second using stubs.
method 1 - interface
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 }
method 2 - stubs
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"); } }
more info in case there issues using cast<>() function, doesn't actual cast. compiled result looks like:
private static void main(string[] args) { customer c = new customer(); isomething cc = c; cc.somemethod(); }
Comments
Post a Comment