I wrote an example like this
Simple Calculator class :
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
implemented "IInterceptor" that provided by DynamicProxy
[Serializable]
public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}
Created an Interceptor class and inherited from "Interceptor" class
public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Start");
}
protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("End");
}
}
but when I used it NOT working !!!
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
var r = c.Add(11, 22);
Console.WriteLine(r);
Console.ReadKey();
}
I excepted to see something like this :
START
33
END
but only show
33
How I can correct it ?!
Try to make the method Add virtual.
public class Calculator
{
public virtual int Add(int a, int b)
{
return a + b;
}
}
The proxy generator creates a new class inheriting Calculator. Thus, the method Add gets an override to make interception possible.
The other option is to make an ICalculator interface
public interface ICalculator
{
int Add(int a, int b);
}
and inherit your class from this interface
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Your dynamic proxy would then use the CreateInterfaceProxyWithTarget method
var proxyGenerator = new ProxyGenerator();
ICalculator calculator = new Calculator()
var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(
calculator,
ProxyGenerationOptions.Default,
new CalculatorInterceptor());
Console.WriteLine(proxy.Add(1, 2));
This gets rid of the virtual from your Calculator class, which in my opinion is bad design unless you have reason to override the method in the future.
You have to use the correct overload and pass in both the target object and the interceptor you wish to use. Method should look something like this:
var proxy = generator.CreateClassProxy<Calculator>(new Calculator(), new CalculatorInterceptor() );
Related
I've read other threads and Eric Lippert's posts on the subject, but haven't seen this exact situation addressed anywhere.
C# optional parameters on overridden methods
Optional parameters and inheritance
I'm trying to implement the following situation:
public class BaseClass
{//ignore rest of class for now
public void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{//ignore rest of class for now
new public void DoThings(String str, Int32 someint = 1)
{
//dostuff but including someint, calls base:DoThings in here
}
}
When I do this the compiler gives me the warning in the subject line that I do not need to use the new keyword because the method does not hide the inherited method. However I do not see a way to call the base method from the object instance, so it looks hidden to me.
I want it to actually be hidden. If it is not hidden, there is potential for some other user to some day call the base method directly and break the class (it involves thread safety).
My question is, does the new method actually hide the inherited method (compiler is wrong?) or is the compiler correct and I need to do something else to hide the original method? Or is it just not possible to achieve the desired outcome?
void DoThings(String str) accepts a single parameter
void DoThings(String str, Int32 someint = 1) accepts two parameters
=> the methods are distinct, unrelated methods, which incidentally share the name.
Default parameters are inserted at the call-sites during compilation.
Here is one possible solution:
public class BaseClass
{
public virtual void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{
public override void DoThings(String str)
{
DoThings(str, 1); // delegate with default param
}
public void DoThings(String str, Int32 someint)
{
//dostuff
}
}
Note that new makes it possible to call base classes' virtual methods in the first place by having a reference with static type of the base class (e.g. by casting it to the base class):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
new public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
base: b
base: c
If you want callers to never call the overridden method of a base class, mark it virtual and override it (like already shown at the top of this answer):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public virtual void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
// "hide" (override) your base method:
public override void DoThings(String str)
{
// delegate to method with default param:
this.DoThings(str);
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
derived: b
base: b
derived: c
base: c
After discussion in the comments: you do not want to use inheratince here, but rather opt for compisition.
The code could look like the following:
public class Test
{
public static void Main()
{
var obj = new DerivedClass(new BaseClass());
obj.DoThings("a");
// baseObj.DoThings("b"); // not accessible
// ((BaseClass)obj).DoThings("c"); // InvalidCastException!
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class Wrapper
{
private BaseClass original;
public Wrapper(BaseClass original) {
this.original = original;
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("wrapped: " + str);
original.DoThings(str);
}
}
Output:
base: a
wrapped: a
the 'new' keyword can't be used where you used it
To hide the member:
public class BaseClass
{ // ignore rest of class for now
public virtual void DoThings(String str)
{
// dostuff
}
}
public class DerivedClass: BaseClass
{ //ignore rest of class for now
public override void DoThings(String str)
{
// dostuff
}
public void DoThings(String str, Int32 someint = 1)
{
// do stuff but including some int, calls base:DoThings in here
}
}
namespace DynamicInterception
{
public class Calculator
{
public virtual int Div(int a, int b)
{
try
{
return a / b;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return 0;
}
}
}
[Serializable]
public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}
public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Start: {0}", invocation.Method.Name);
}
protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("End: {0}", invocation.Method.Name);
}
}
class Program
{
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
var r = c.Div(11, 0);
Console.ReadKey();
}
}
}
Is it possible to replace public virtual int Div(int a,int b)
with interface
interface ICalculator
{
int Div(int a, int b);
}
How then should look like proxy declaration?
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
If you want to add an interface to the Calculator and to execute those 2 lines
it will work the same:
public interface ICalculator
{
int Div(int a, int b);
}
public class Calculator : ICalculator
{
public int Div(int a, int b)
{
try
{
return a / b;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return 0;
}
}
}
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
But you didn't really do anything by that - you are still creating the proxy for a concrete derived type. I assume you want something like "CreateClassProxy<ICalculator>". That won't work because the CreateClassProxy has a generic constraint on where TClass : class.
What you do have is a variety of CreateInterfaceProxt.. Methods which you can try. But still a naive execution like the following won't work:
ICalculator c = generator.CreateInterfaceProxyWithoutTarget<ICalculator>(new CalculatorInterceptor());
c.Div(1, 2);
It will execute, call the interceptor and will fail when running the invocation.Proceed(); with the error:
System.NotImplementedException This is a DynamicProxy2 error: The
interceptor attempted to 'Proceed' for method 'Int32 Div(Int32,
Int32)' which has no target. When calling method without target there
is no implementation to 'proceed' to and it is the responsibility of
the interceptor to mimic the implementation (set return value, out
arguments etc)
So as the good indicative (seriously) errors of Castle specify - you must somehow have an implementation for it - or by indicating it yourself in the interceptor - of by having a Component registered for that interface.
Instead you can do like this: (Check comments in code)
ProxyGenerator generator = new ProxyGenerator();
ICalculator calculator = new Calculator();
var proxyCalculator = generator.CreateInterfaceProxyWithTarget(typeof(ICalculator),calculator, new CalculatorInterceptor());
calculator.Div(1, 2); // Will execute but will not be intercepted
((ICalculator)proxyCalculator).Div(11, 0); //Will execute and will be intercepted
But after saying all I said above, if the purpose behind all of this is to have an interceptor intercept your method then just just the "good-old" registering to the container:
WindsorContainer container = new WindsorContainer();
container.Register(
Component.For<CalculatorInterceptor>(),
Component.For<ICalculator>()
.ImplementedBy<Calculator>()
.Interceptors<CalculatorInterceptor>());
var calculator = container.Resolve<ICalculator>();
calculator.Div(1, 0);
// Output:
// Start: Div
// Attempted to divide by zero
// End: Div
i have created same name methods in base and derived classes and i am able to create
class Program
{
public void CalculateArea(int a,int b)
{
Console.WriteLine(a*b);
}
}
class progrmm1:Program
{
public void CalculateArea(int a ,int b)
{
Console.WriteLine(a + b);
}
static void Main(string[] args)
{
progrmm1 obj = new progrmm1();
Program obj1 = new Program();
obj.CalculateArea(4,5);
obj1.CalculateArea(4,5);
Console.ReadLine();
}
}
then why i need to use virtual and override
If you don't use virtual and override then you are not taking advantage of polymorphism. Basically the CalculateArea in the derived class is hiding the one in the base class. That means that if you reference an object of the derived class type as the base it will call the CalculateArea in the base class instead of the derived one. Where as if you use virtual and override it would call the Derived method even if it where referenced as the Base.
For example with these classes
public class Base
{
public void DoSomething()
{
Console.WriteLine("Base.DoSomething");
}
}
public class Derived : Base
{
public void DoSomething()
{
Console.WriteLine("Derived.DoSomething");
}
}
This code
Base derivedAsBase = new Derived();
derivedAsBase.DoSomething();
will output
Base.DoSomething
but using virtual and override
public class Base
{
public virtual void DoSomething()
{
Console.WriteLine("Base.DoSomething");
}
}
public class Derived : Base
{
public override void DoSomething()
{
Console.WriteLine("Derived.DoSomething");
}
}
The same code
Base derivedAsBase = new Derived();
derivedAsBase.DoSomething();
will output
Derived.DoSomething
When overridden, the method on the most derived class is called. Observe this slightly modified code where I assign two Program instances. One from a Program and one from a program1:
class Program
{
public virtual void CalculateArea(int a, int b)
{
Console.WriteLine(a * b);
}
}
class progrmm1 : Program
{
public override void CalculateArea(int a, int b)
{
Console.WriteLine(a + b);
}
static void Main(string[] args)
{
Program obj = new progrmm1();
Program obj1 = new Program();
obj.CalculateArea(4, 5);
obj1.CalculateArea(4, 5);
Console.ReadLine();
}
}
OUTPUT:
9
20
And now, observe non-virtual:
class Program
{
public void CalculateArea(int a, int b)
{
Console.WriteLine(a * b);
}
}
class progrmm1 : Program
{
public void CalculateArea(int a, int b)
{
Console.WriteLine(a + b);
}
static void Main(string[] args)
{
Program obj = new progrmm1();
Program obj1 = new Program();
obj.CalculateArea(4, 5);
obj1.CalculateArea(4, 5);
Console.ReadLine();
}
}
OUTPUT
20
20
First you need to know about Virtual Method.
Basically A virtual method is a method that can be redefined in
derived classes. A virtual method has an implementation in a base
class as well as derived the class.
Example:
Let Suppose we have two classes, A and B. Class A has a public virtual method called Test. Class B, meanwhile, derives from class A and it provides a public override method called Test as well.
using System;
class A
{
public virtual void Test()
{
Console.WriteLine("A.Test");
}
}
class B : A
{
public override void Test()
{
Console.WriteLine("B.Test");
}
}
class Program
{
static void Main()
{
// Compile-time type is A.
// Runtime type is A as well.
A ref1 = new A();
ref1.Test();
// Compile-time type is A.
// Runtime type is B.
A ref2 = new B();
ref2.Test();
}
}
Output
A.Test
B.Test
Why would you need to use virtual methods?:
Your program may be designed in such a way that you do not know all the types of objects that will occur when it is executed. You can provide a standard (base) type and design around that type.
Then, you can re-implement important functionality depending on the more specific (derived) types. When you call a method on the base type, you invoke the more derived (and useful) method.
Let's say I have an interface IFoo
interface IFoo
{
int Bar();
int Bar2();
void VBar();
//etc,
}
Can I create a wrapper that takes any IFoo object and do something before/after the actual call?
e.g. when I do something like this
IFoo wrappedFoo = new Wrapper<IFoo>(actualFooObject).Object;
wrappedFoo.Bar();
then the wrapper.Bar() method actually execute something like this
PreCall(); //some code that I can define in the wrapper
actualFooObject.Bar();
PostCall();
Is there a simple and clean way to do this?
You can use Code Contracts for this approach. Take a look on section 2.8 Interface Contracts of user manual (pdf).
You can use AOP. I´ve been using this library for quite some time now:
http://www.postsharp.net/products
if you need to have something on PreCall() and PostCall , the simple way is to wrap under the proxy base approach
public abstract class ProxyBase
{
public void Execute()
{
PreCondition();
Call();
PostCondition();
}
private void PreCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
private void PostCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
protected abstract void Call();
}
public class AppProxy<T> : ProxyBase where T : IApp
{
private IApp _app;
public AppProxy<T> Init(IApp app)
{
_app = app;
return this;
}
protected override void Call()
{
Console.WriteLine("AppProxy.Call()");
_app.Call();
}
public IApp Object
{
get { return _app; }
}
}
public interface IApp
{
void Call();
}
public interface IFoo : IApp
{
}
public class ActualFoo : IApp
{
public void Call()
{
Console.WriteLine("ActualFoo.Call()");
}
}
class Program
{
static void Main(string[] args)
{
ActualFoo actualFoo = new ActualFoo();
var app = new AppProxy<IFoo>().Init(actualFoo);
app.Execute();
var o = app.Object as ActualFoo;
Console.ReadLine();
}
}
--------------- Output --------------
ProxyBase.PreCondition()
AppProxy.Call()
ActualFoo.Call()
ProxyBase.PreCondition()
I don't see a "clean and simple" way of doing this.
The best option I can come up with is writing a generic Wrapper<T> that encapsulates and instance of T and implements generic Precall and Postcall methods:
public class Wrapper<T>
{
protected T _instance;
public Wrapper(T instance)
{
this._instance = instance;
}
protected virtual void Precall()
{
// do something
}
protected virtual void Postcall()
{
// do something
}
}
So that you can write your own FooWrapper for interface IFoo (or any other interface) and just delegate method calls:
public class FooWrapper :Wrapper<IFoo>, IFoo
{
public FooWrapper(IFoo foo)
: base(foo)
{
}
public int Bar()
{
base.Precall(); return base._instance.Bar(); base.Postcall();
}
public int Bar2()
{
base.Precall(); return base._instance.Bar2(); base.Postcall();
}
public void VBar()
{
base.Precall(); base._instance.VBar(); base.Postcall();
}
}
So you can use it like this:
IFoo f = new ActualFooClass();
IFoo wf = new FooWrapper(f);
f.Bar();
Of course, if your Precall and Postcall methods are not generic, then there is really no point in using the Wrapper<T> class. Just go with the FooWrapper.
Without any code in the subclasses, I'd like an abstract class to have a different copy of a static variable for each subclass. In C#
abstract class ClassA
{
static string theValue;
// just to demonstrate
public string GetValue()
{
return theValue;
}
...
}
class ClassB : ClassA { }
class ClassC : ClassA { }
and (for example):
(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"
My current solution is this:
abstract class ClassA
{
static Dictionary<Type, string> theValue;
public string GetValue()
{
return theValue[this.GetType()];
}
...
}
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
This is similar to Can I have different copies of a static variable for each different type of inheriting class, but I have no control over the subclasses
There is a more elegant way. You can exploit the fact that statics in a generic base class are different for each derived class of a different type
public abstract class BaseClass<T> where T : class
{
public static int x = 6;
public int MyProperty { get => x; set => x = value; }
}
For each child class, the static int x will be unique for each unique T
Lets derive two child classes, and we use the name of the child class as the generic T in the base class.
public class ChildA: BaseClass<ChildA>
{
}
public class ChildB : BaseClass<ChildB>
{
}
Now the static MyProperty is unique for both ChildA and ChildB
var TA = new ChildA();
TA.MyProperty = 8;
var TB = new ChildB();
TB.MyProperty = 4;
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
There isn't really a built-in way of doing this, as you're kind of violating basic OO principles here. Your base class should have no knowledge of subclasses in traditional object oriented theory.
That being said, if you must do this, your implementation is probably about as good as you're going to get, unless you can add some other info to the subclasses directly. If you need to control this, and you can't change subclasses, this will probably be your best approach.
This is a little different than what you're asking for, but perhaps accomplishes the same thing.
class Program
{
static void Main(string[] args)
{
Console.WriteLine((new B()).theValue);
Console.WriteLine((new C()).theValue);
Console.ReadKey();
}
}
public abstract class A
{
public readonly string theValue;
protected A(string s)
{
theValue = s;
}
}
public class B : A
{
public B(): base("Banana")
{
}
}
public class C : A
{
public C(): base("Coconut")
{
}
}
There's an alternative solution which might or might not be better than yours, depending on the use case:
abstract class ClassA
{
private static class InternalClass<T> {
public static string Value;
}
public string GetValue()
{
return (string)typeof(InternalClass<>)
.MakeGenericType(GetType())
.GetField("Value", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
}
This approach is used in EqualityComparer<T>.Default. Of course, it's not used for this problem. You should really consider making GetValue abstract and override it in each derived class.
What about this?
class Base {
protected static SomeObjectType myVariable;
protected void doSomething()
{
Console.WriteLine( myVariable.SomeProperty );
}
}
class AAA : Base
{
static AAA()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "A";
}
}
class BBB : Base
{
static BBB()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "B";
}
}
It works for me.
Would be even nicer with Interface.
Simple solution: just use word "new".
public abstract class AbstractClass
{
public static int Variable;
}
public class RealizationA : AbstractClass
{
public new static int Variable;
}
public class RealizationB : AbstractClass
{
public new static int Variable;
}
And the result:
AbstractClass.Variable = 1;
RealizationA.Variable = 2;
RealizationB.Variable = 3;
Console.WriteLine(AbstractClass.Variable); //1
Console.WriteLine(RealizationA.Variable); //2
Console.WriteLine(RealizationB.Variable); //3
or you can use property:
//in abstract class
public static int Variable {get; set;}
//in child class
public static new int Variable {get; set;}
or function (but remember to add "new" to both variable and function):
//in abstract class
protected static int Variable;
public static int GetVariable() { return Variable; }
public static void SetVariable(int v) { Variable = v; }
//in child class
protected new static int Variable;
public static new int GetVariable() { return Variable; }
public static new void SetVariable(int v) { Variable = v; }
or you can use private variables (you don't need to use "new") with functions to get and set:
//in abstract class
private static int Variable;
//get and set methods
//in child class
private static int Variable;
//get and set methods