I have the protected variable var1 in the abstract class AbstractModule
I create abstract class AbstractActivity : AbstractModule and use var1 from the parent class AbstractModule
Now I create class MyActivity : AbstractActivity and I want to make var1 not accessible in the MyActivity class.
How can I do it?
(I can create the protected property, but then I have the same problem)
C# does not allow this. But you can shadow the field in your class AbstractActivity by creating one with the same name. Your class MyActivity would then have access to the shadowed field and its value, but not to the field defined in AbstractModule.
public class A
{
protected bool seeMe;
}
public class B : A
{
public B()
{
base.seeMe = false; // this is A.seeMe
}
protected bool seeMe;
}
public class C : B
{
public C()
{
seeMe = true; // this is B.seeMe
}
}
The above example doesn't prevent code from being written that uses the shadow field. This may cause confusion if the programmer is aware of A.seeMe and thinks it is being set. You can force a compile error when B.seeMe is used by decorating it with the Obsolete attribute:
public class B : A
{
public B()
{
base.seeMe = false; // this is A.seeMe
}
[Obsolete("cannot use seeMe", error:true)]
protected bool seeMe;
}
public class C : B
{
public C()
{
seeMe = true; // this will give a compile error
}
}
Same example with above solutions with int value.
I trying to restrict grand parent field in child class with the same name.
public class MyClass
{
protected int myValue = 10;
}
public class MyClass1 : MyClass
{
protected int myValue = 15;
public MyClass1()
{
base.myValue = 25;
this.myValue = 11;
}
}
public class MyClass2 : MyClass1
{
public void print()
{
Console.WriteLine("My Value : " + myValue);//this will print 11
}
}
class Program
{
static void Main(string[] args)
{
MyClass2 myClass2 = new MyClass2();
myClass2.print();
}
}
//Restrict grand parent method in child class using sealed keyword
public class MyClass
{
protected virtual void MyMethod()
{
}
}
public class MyClass1 : MyClass
{
// because of sealed method this method will not going to override in derived class.
sealed override protected void MyMethod()
{
}
}
public class MyClass2 : MyClass1
{
protected override void MyMethod()//this will give compiler error
{
}
}
Related
I'm trying to get the ClicksCounter from FableScript child class' value to another child class and I don't know how to transfer the value. From what I achieved, the ClicksCounter are read by the parent class (GameManagerRevamped) successfully, but on the BattleSystem child class it seems that the values are not transported there.
Assuming this is my Parent Class
public class GameManagerRevamped : MonoBehaviour
{
public int ClicksCounter;
public virtual void firstButtonClicked()
{
Debug.Log(ClicksCounter);
}
}
My Child class which is FableScript
public class FableScript : GameManagerRevamped
{
public override void firstButtonClicked()
{
ClicksCounter += 1;
base.firstButtonClicked();
}
}
And my 3rd child class BattleSystem is where I'm trying to get the value of ClicksCounter
public class BattleSystem : GameManagerRevamped
{
public void BattleButton()
{
//Output is 0 here
Debug.Log("Battle Counter is" + ClicksCounter);
}
}
My goal is when the user clicks on the button (FableScript) it will increment and be read by BattleSystem.
One option is the make the click counter static in the base class. This is if it is ok that it shares that property between all child classes.
class Program
{
static void Main(string[] args)
{
var childClass1 = new ChildClass1();
var childClass2 = new ChildClass2();
childClass1.IncrementCounter();
childClass2.ConsoleLogCounter();
}
}
public class BaseClass
{
public static int counter;
}
public class ChildClass1 : BaseClass
{
public void IncrementCounter()
{
counter++;
}
}
public class ChildClass2 : BaseClass
{
public void ConsoleLogCounter()
{
Console.WriteLine(counter);
}
}
The code is simple enough to understand I hope.
I'm trying to use an interface type IColor in order to pass color objects to the ColorManager. I then want the ColorManager to pass this object to the IColor object as its own type, so the method overloads gets called.
However, it seems since it is being passed as the IColor type, C# will not implicity cast it into its complete type as either a BlueColor or GreenColor.
I hope this makes some sense to somebody on what I want to achieve. Is this possible in C#?
[Solution]
http://msdn.microsoft.com/en-us/library/dd264736.aspx
Overload Resolution with Arguments of Type dynamic
My code so far:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Example
{
public interface IColor
{
void CatchColor(IColor c);
}
public class BlueColor : IColor
{
public void CatchColor(IColor c)
{
}
}
public class GreenColor : IColor
{
public void CatchColor(BlueColor c)
{
Console.WriteLine("CAUGHT BLUE!");
}
public void CatchColor(GreenColor c)
{
Console.WriteLine("CAUGHT GREEN!");
}
public void CatchColor(IColor c)
{
Console.WriteLine("CAUGHT SOME COLOR!");
}
}
public class ColorManager
{
public void PassColor(IColor c)
{
// Don't use static type-checking
// Problem solved
dynamic AnyColor = c;
AnyColor.CatchColor(AnyColor);
}
public static void Main()
{
GreenColor G = new GreenColor();
new ColorManager().PassColor(G);
Console.ReadLine();
return;
}
}
}
One possiblity to tell the ColorManager class to use the correct type of the passed object is to use an abstract class, that already implements the CatchColor:
public abstract class IColor
{
// override in every class
public abstract void PrintColor();
// has the correct type passed with the interface
public void CatchColor(IColor c)
{
c.PrintColor();
}
}
Then the sub classes need to implement only PrintColor with the correct color:
public class BlueColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("BLUE!");
}
}
public class GreenColor : IColor
{
public override void PrintColor()
{
Console.WriteLine("GREEN!");
}
}
The manager is the same:
public class ColorManager
{
public void PassColor(IColor c)
{
c.CatchColor(c);
}
}
It can be used like this:
GreenColor G = new GreenColor();
var cm = new ColorManager();
cm.PassColor(G);
cm.PassColor(new BlueColor());
The outputs is:
GREEN!
BLUE!
What you want is late method binding.
The downside to this is you have to add methods for each new type of color. The upside is you don't have to maintain a case statement or conditional logic.
See here for more detail:
Early and late binding
Edit: Here is a working example of this type of late-binding.
class Program {
static void Main(string[] args) {
//Declare instances
BaseClass myClass = new Class2();
BaseClass otherClass = new Class1();
//Invoke the action method which will match based on the BaseClass type
Action(myClass);
Action(otherClass);
Console.ReadLine();
}
public static void Action(BaseClass classType) {
//Remove the compile-time type so the runtime can select the method based on signature
dynamic aClass = classType;
ServiceMethod(aClass);
}
public static void ServiceMethod(dynamic input) {
Methods(input);
}
public static void Methods(Class1 classType) {
Console.WriteLine("Class1");
Debug.WriteLine("Class1");
}
public static void Methods(Class2 classtype) {
Console.WriteLine("Class2");
Debug.WriteLine("Class2");
}
public static void Methods(Class3 classType) {
Console.WriteLine("Class3");
Debug.WriteLine("Class3");
}
}
public abstract class BaseClass { //This could also be an interface
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Class1 : BaseClass {
}
public class Class2 : BaseClass{
}
public class Class3 : BaseClass {
}
So you want something like:
public void CatchColor(Color c)
{
if (c is BlueColor)
CatchColor(c as BlueColor);
if (c is GreenColor)
CatchColor(c as GreenColor);
}
?
is this possible to somehow, have this scenario, where A.N inherits code from A with this code example?
The reason for setting it up like this, is that I need multiple classes that inherit from Base<TType> and the Nested : Base<TType> where the server has the base only, and the client has the extended Nested. This way, it would be easy to use the code, where they would have some shared code between themselves & each other.
The problem is that I would have to write identical code inside the
A and A.N
B and B.N
C and C.N
etc.
I have solved this temporarily, by replacing the Nested abstract class, with an Interface and doing
A.N : A, INested, but now I have to rewrite the Base<TType>.Nested code again inside all the Nested classes. For now, the nested class is small & managable.
hope this isn't a confusing question...
public abstract class Base<TType> where TType : class
{
public TType data;
internal void CommonCodeForAll() { }
public abstract void Update();
public abstract class Nested : Base<TType>
{
public abstract void Input();
}
}
public class A : Base<someClass>
{
public float Somevariable;
public void SpecificFunctionToA() { }
public override void Update()
{
// code that gets executed on server & client side that is unique to A
}
public class N : A.Nested
{
public override void Input()
{
if (data.IsReady()) { Somevariable *= 2; }
SpecificFunctionToA();
}
}
}
public class B : Base<anotherClass>
{
public float Somevariable;
public int index;
public int[] Grid;
public void SomethingElse() { }
public override void Update()
{
// code that gets executed on server & client side that is unique to B
}
public class N : B.Nested
{
public override void Input()
{
if (Grid[index] == -1) { SomethingElse(); }
data.Somevariable = Grid[index];
}
}
}
Edit:
I updated the code example to show what I'm trying to achieve.
Why I am trying to do this, is to keep the physics, networking & User input seperate.
There are multiple different controllers where each one has their own pack & unpacking functions, controller identity & access to the physics engine.
I have a solution using ecapsulation of classes instead of inheritance.
public abstract class BaseGeneric<T>
{
T data;
// ctor
protected BaseGeneric(T data)
{
this.data=data;
}
// methods
public abstract void Update();
// properties
public T Data
{
get { return data; }
set { data=value; }
}
// base nested class
public abstract class BaseNested<B> where B : BaseGeneric<T>
{
protected B #base;
// ctor
protected BaseNested(B #base)
{
this.#base=#base;
}
// methods
public abstract void Input(T data);
public void Update() { #base.Update(); }
// properties
public T Data
{
get { return #base.data; }
set { #base.data=value; }
}
}
}
// implementation base
public class Base : BaseGeneric<int>
{
// ctor
protected Base(int data) : base(data) { }
//methods
public override void Update()
{
this.Data+=1;
}
// implemented nested class
public class Nested : Base.BaseNested<Base>
{
// ctor
public Nested(int data) : base(new Base(data)) { }
public Nested(Base #base) : base(#base) { }
// methods
public override void Input(int data)
{
this.Data=data;
}
}
}
class Program
{
static void Main(string[] args)
{
// new implemented class with value 0
var nested=new Base.Nested(0);
// set value to 100
nested.Input(100);
// call update as implemented by `Base`.
nested.Update();
}
}
Consider a namespace defined in .NET framework with a class hierarchy.
namespace OfficialDotnetNS
{
namespace officialNS.Bases
{
public class BaseOfA : IFakeA, IFakeB
{
protected void Driver(Stream stream){ this.DriveFoo(stream); };
protected internal virtual void DriveFoo(Stream stream);
}
}
public abstract class A : officialNS.Bases.BaseofA
{
protected internal override void DriveFoo(Stream stream){ this.Foo(stream); };
protected virtual void Foo(String stream);
}
public class B : A {}
public class C : A {}
public class D : A {}
// and 50+ similar classes derived from A
}
I have a BaseofA object and when I call Driver(stream) it subsequently calls Foo of A and that of suitable derived class.
Now, I want to override Foo() with same code, so all classes derived from A inherit this custom implementation.
One way is to write custom wrapper for each class:
public class CustomB : B
{
protected override void Foo(Stream stream)
{
stream.Position = 12;
base.Foo(stream);
}
}
public class CustomC : C
{
protected override void Foo(Stream stream)
{
stream.Position = 12;
base.Foo(stream);
}
}
public class CustomD : D
{
protected override void Foo(Stream stream)
{
stream.Position = 12;
base.Foo(stream);
}
}
//.. for all 50+ classes
Can we do this using reflection or some other technique without repeating code?
Yes. It's called proxying and it's a technique used by entity framework. There are several ways of achieving this, but IMO the best is the CastleProject DynamicProxy.
For instance (a simplified case, but I think this does what you want):
void Main()
{
var pg = new Castle.DynamicProxy.ProxyGenerator();
var typeA = typeof(A);
var interceptor =
new FooInterceptor(
str => Console.WriteLine("intercepted {0}", str));
IEnumerable<A> objs = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsSubclassOf(typeA))
.Select(t => (A)(pg.CreateClassProxy(t, interceptor)));
foreach(A a in objs)
{
a.CallFoo("hello world");
}
}
public class A
{
public void CallFoo(string someString){
Foo(someString);
}
protected virtual void Foo(string someString)
{
Console.WriteLine("base Foo {0}", someString);
}
}
public class B : A {}
public class C : A {}
public class D : A {}
public class FooInterceptor : IInterceptor
{
Action<string> interceptorDelegate;
public Interceptor(Action<string> interceptorDelegate)
{
this.interceptorDelegate = interceptorDelegate;
}
public void Intercept(IInvocation invocation)
{
var isFooCall = invocation.Method.Name == "Foo";
if(isFooCall)
{
interceptorDelegate
.Invoke((string)(invocation.Arguments[0]));
}
else
{
invocation.Proceed();
}
}
}
I have an abstract class A, where I have derived the classes B and C.
Class A provides an abstract method DoJOB(), which is implemented by both derived classes.
There is a class X which has methods inside, which need to call DoJOB().
The class X may not contain any code like B.DoJOB() or C.DoJOB().
Example:
public class X
{
private A foo;
public X(A concrete)
{
foo = concrete;
}
public FunnyMethod()
{
foo.DoJOB();
}
}
While instantiating class X I want to decide which derived class (B or C) must be used.
I thought about passing an instance of B or C using the constructor of X.
X kewl = new X(new C());
kewl.FunnyMethod(); //calls C.DoJOB()
kewl = new X(new B());
kewl.FunnyMethod(); // calls B.DoJOB()
My test showed that declaring a method with a parameter A is not working. Am I missing something?
How can I implement this correctly?
(A is abstract, it cannot be instantiated)
EDIT:
Sorry, I forgot sth.
class A is a generic abstract singleton:
abstract public class A<T> where T : A<T>
{
....
}
public sealed class B : A<B>
{
.....
}
public sealed class C : A<C>
{
.....
}
See the example:
http://www.c-sharpcorner.com/UploadFile/snorrebaard/GenericSingleton11172008110419AM/GenericSingleton.aspx
Under the head line "The solution with the Generic Singleton as an abstract class"
You must have made a mistake in the test, the code works fine:
void Main()
{
X kewl = new X(new C());
kewl.FunnyMethod(); //calls C.DoJOB()
kewl = new X(new B());
kewl.FunnyMethod(); // calls B.DoJOB()
}
public class X
{
private A foo;
public X(A concrete)
{
foo = concrete;
}
public void FunnyMethod()
{
foo.DoJOB();
}
}
public abstract class A
{
public abstract void DoJOB();
}
public class B : A
{
public override void DoJOB()
{
Console.WriteLine("B");
}
}
public class C : A
{
public override void DoJOB()
{
Console.WriteLine("C");
}
}
Outputs :
C
B
For your edit:
void Main()
{
var kewl = new X<C>(new C());
kewl.FunnyMethod(); //calls C.DoJOB()
var kewl2 = new X<B>(new B());
kewl2.FunnyMethod(); // calls B.DoJOB()
}
public class X <T> where T : A<T>
{
private A<T> foo;
public X(A<T> concrete)
{
foo = concrete;
}
public void FunnyMethod()
{
foo.DoJOB();
}
}
public abstract class A<T> where T : A<T>
{
public abstract void DoJOB();
}
public class B : A<B>
{
public override void DoJOB()
{
Console.WriteLine("B");
}
}
public class C : A<C>
{
public override void DoJOB()
{
Console.WriteLine("C");
}
}
Works for me. I get the expected
I did something interesting!
So Did I!
when I run it.
Paste this in your Visual Studio and smoke it
using System;
namespace TestDrive
{
class Program
{
static void Main( string[] args )
{
ServiceConsumer x = new ServiceConsumer( new ConcreteService2() ) ;
x.FunnyMethod() ;
return ;
}
}
abstract class AbstractService
{
public abstract void DoSomethingInteresting() ;
}
class ConcreteService1 : AbstractService
{
public override void DoSomethingInteresting()
{
Console.WriteLine("I did something interesting!");
return ;
}
}
class ConcreteService2 : ConcreteService1
{
public override void DoSomethingInteresting()
{
base.DoSomethingInteresting() ;
Console.WriteLine("So Did I!");
return ;
}
}
class ConcreteService : AbstractService
{
public override void DoSomethingInteresting()
{
Console.WriteLine("Not It's my turn to do something interesting!") ;
return ;
}
}
class ServiceConsumer
{
private AbstractService Service ;
public ServiceConsumer( AbstractService serviceInstance )
{
this.Service = serviceInstance ;
return ;
}
public void FunnyMethod()
{
Service.DoSomethingInteresting() ;
return ;
}
}
}
Cheers!
I'm not sure I understand the question, here is my implementation and it works:
namespace CSharpConsole {
public abstract class A {
public abstract void Test();
}
public class B : A {
public override void Test() {
System.Console.WriteLine("B:Test called!");
}
}
public class C : A {
public override void Test() {
System.Console.WriteLine("C:Test called!");
}
}
class Program {
private A _concrete;
public Program(A concrete) {
_concrete = concrete;
}
public void DoTest() {
_concrete.Test();
}
static void Main(string[] args) {
Program pb = new Program(new B());
pb.DoTest();
Program pc = new Program(new C());
pc.DoTest();
}
}
}