I'm having a base class defined in my app
Something like,
using System;
public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}
}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}
Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.
How do I do that ?
I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:
var obj = new BaseClass();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
My guess would be that what you actually want here is some form of injection; for example:
public class BaseClass
{
private readonly IFunctionality1 functionality1;
public virtual void Method2() { Console.WriteLine("base2"); }
public virtual void Method1() { this.functionality1.Method1(); }
public BaseClass(IFunctionality1 functionality1)
{
this.functionality1 = functionality1;
}
}
public class Derived1 : BaseClass
{
public Derived1(IFunctionality1 functionality1) : base (functionality1)
{
}
}
In this case, you might find that inheritance isn't even required anymore.
Related
Assume that I have the following classes with a generic interface:
public class MyClass_1 : IGenericInterface
{
public void foo()
{
bar();
}
void bar()
{
...
}
}
public class MyClass_2 : IGenericInterface
{
public void foo()
{
bar();
}
void bar()
{
...
}
}
public interface IGenericInterface
{
void foo();
}
They both have the public "foo" function and it's implementation is the same as well. So I tend to move "foo" into an abstract, shouldn't I?
Now, the problem is, that they call a private function ("bar") which is a class specific implementation. How can I make this function "bar" kind of visible to the possibly generic implementation of "foo"?
E.g.
public abstract class MyGenericClass: IGenericInterface
{
public foo()
{
bar();
}
}
The goal then would be that the specific class inherit from the generic class:
public class MyClass_1 : GenericClass
{
private void bar()
{
...
}
}
public class MyClass_2 : GenericClass
{
private void bar
{
...
}
}
Define bar as abstract:
public abstract class MyGenericClass: IGenericInterface
{
protected abstract void bar();
public foo()
{
bar();
}
}
Then bar can be implemented differently in each subclass, but the base class can be sure it exists:
public class MyClass_1 : GenericClass
{
protected override void bar
{
// ...
}
}
Make it an abstract protected method in your base class:
public abstract class MyGenericClass: IGenericInterface
{
public foo()
{
bar();
}
protected abstract void bar();
}
Protected means that it will be visible in all derived classes, abstract means that your derived classes have to implement it (if they are not abstract themselves).
I want to reuse Cook method functionality, but still pass different parameters to execute:
public void Cook(BasicRequest request,IBaseInterface base)
{
// Some code
// More code
request.Execute(base);
}
public class BasicRequest
{
public abstract void Execute(IBaseInterface baseInterface)
}
public class RequestA : BasicRequest
{
public void Execute(IBaseInterface base)
{
var derived = (DerivedClassA)base;
// Do stuff with derived
}
}
public class RequestB : BasicRequest
{
public void Execute(IBaseInterface base)
{
var derived = (DerivedClassB)base;
// Do stuff with derived
}
}
public interface IDerivedClassA : IBaseInterface {}
public interface IDerivedClassB : IBaseInterface {}
I have a design issue here that casting is needed on each of requests execute methods.
How can I make this code cleaner ?
You should be using generics.
Update the BaseRequest to a generic class:
public abstract class BasicRequest<T> where T:IBaseInterface
{
public abstract void Execute(T baseInterface);
}
Change your class Cook method as follows:
public void Cook<T>(BasicRequest<T> request, T ibase) where T:IBaseInterface
{
// Some code
// More code
request.Execute(ibase);
}
Change your classes,
public class RequestA : BasicRequest<DerivedClassA>
{
public override void Execute(DerivedClassA ibase)
{
// Do stuff with derived
}
}
public class RequestB : BasicRequest<DerivedClassB>
{
public override void Execute(DerivedClassB ibase)
{
// Do stuff with derived
}
}
I'm trying to implement a generic abstract method with a type constraint, then Implement it multiple times using different specified types.
public abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
public class DashAbility : Ability
{
public override void BindToStation<NavStation>(NavStation station){ }
public override void BindToStation<CannonStation>(CannonStation station){ }
}
But I get an error which says the method has already been defined with the same paramater types.
I'm guessing that the compiler treats any generic paramater as the same in terms of the method signature, so these two methods look the same to it.
Still though, I'm wondering if theres a way to have generic method overloading using specific types.. ?
You can't do exactly what you want, but you can try an approach like this:
interface IBindableTo<T> where T : Station
{
void BindToStation(T station);
}
abstract class Ability
{
public abstract void BindToStation<T>(T station) where T : Station;
}
class DashAbility : Ability, IBindableTo<NavStation>, IBindableTo<CannonStation>
{
public override void BindToStation<T>(T station)
{
if (this is IBindableTo<T> binnder)
{
binnder.BindToStation(station);
return;
}
throw new NotSupportedException();
}
void IBindableTo<NavStation>.BindToStation(NavStation station)
{
...
}
void IBindableTo<CannonStation>.BindToStation(CannonStation station)
{
...
}
}
Hope this helps.
C# doesn't support specialization in that way, and neither does C++ easily when you want to specialize on runtime type.
But you can use polymorphism, so you can use double-dispatch:
public abstract class Station {
internal abstract void DashBindToStation();
}
public class NavStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public class CannonStation : Station {
internal override void DashBindToStation() {
throw new NotImplementedException();
}
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public override void BindToStation(Station station) {
station.DashBindToStation();
}
}
Another possibility with C# is to use runtime dispatching using dynamic:
public abstract class Station {
}
public class NavStation : Station {
}
public class CannonStation : Station {
}
public abstract class Ability {
public abstract void BindToStation(Station station);
}
public class DashAbility : Ability {
public void BindToStation(NavStation station) {
}
public void BindToStation(CannonStation station) {
}
public override void BindToStation(Station station) {
BindToStation((dynamic)station);
}
}
Hi everyone I am programming in Unity3d with C# and while I was writing my code I stumbled with a little issue, I write to you an example because I dont know explain me.
class Base
{
public string name;
}
class Derived : Base
{
public void Gun();
}
class BasePlayer
{
public Base x;
}
class SoldierPlayer : BasePlayer
{
}
The situation is this, I want to do something like that
SoldierPlayer.x.Gun();
But I don't know how do it
The real case is this
public class BasePlayerController : MonoBehaviour
{
public BasePlayerManager playerManager;
...
public class RobotPlayerController : BasePlayerController {
...
playerManager = gameObject.AddComponent<RobotPlayerManager>();
And I will use new methods
UPDATE 1
I did a example better, I want to do in Base Controller manager.user.energy and be treated as the next type RobotManager.RobotUser.energy
BaseController
BaseManager
BaseUser
class BaseController
{
BaseManager manager;
public virtual void Move(int x,int y)...
}
class BaseManager {
BaseUser user;
public virtual Pause(bool state);
}
class BaseUser {
int life
}
RobotController
RobotManager
RobotUser
class RobotController : BaseController
{
// manager as RobotManager?
public void Ray(int x,int y);
}
class RobotManager : BaseManager
{
// user as RobotUser?
}
class RobotUser : BaseUser
{
int energy;
}
UPDATE 2
I seek to do this
public Run()
{
RobotController rc = new RobotController();
rc.manager.energy;
}
You can't call SoldierPlayer.x.Gun(); because SoldierPlayer.x has type Base which has not method Gun(). OOP world and C# can provide you many solutions, your choose depends on your goals.
some of them (order by best practise):
1) Overriding Polymorphism. Add .Gun() method to Base class and implemend it in derived classes. For example
class Base
{
public string name;
public void virtual Gun()
{
Trace.Log("I'm base class, i can't do anything");
}
}
class Derived : Base
{
public override void Gun()
{
Consule.WriteLine("Hello i have gun");
}
}
class Derived2 : Base
{
public override void Gun()
{
Consule.WriteLine("Hello i have 2 guns");
}
}
2) Overloading Polymorphism In many source this method is mentioned like some kind of polymorphism AD-HOC
public void GunAction(Derived2 o)
{
o.Gun();
}
public void GunAction(Derived1 o)
{
o.Gun();
}
public void GunAction(Base o)
{
Trace.Log("I'm base class, i can't do anything");
}
3) is-cast
public void GunAction(Base o)
{
if(o is Derived1 )
o.Gun();
if(o is Derived2 )
o.Gun();
}
UPDATE 1 answering to your new requirements
class BaseController
{
public BaseManager manager;
...
class RobotController1 : BaseController
{
// manager as RobotManager? - no it is stil BaseManager
public void Ray(int x,int y);
}
class RobotController2 : BaseController
{
// manager as RobotManager? - yes. now it is RobotManager
public void Ray(int x,int y);
public RobotController2()
{
manager = new RobotManager();
}
}
public void Run()
{
var controller = new RobotController2();// you have RobotManager
controller.manager = new BaseManager();// it is again BaseManager
}
How can I get the type (not a name string, but a type itself) of the current class, in a static method of an abstract class?
using System.Reflection; // I'll need it, right?
public abstract class AbstractClass {
private static void Method() {
// I want to get CurrentClass type here
}
}
public class CurrentClass : AbstractClass {
public void DoStuff() {
Method(); // Here I'm calling it
}
}
This question is very similar to this one:
How to get the current class name at runtime?
However, I want to get this information from inside the static method.
public abstract class AbstractClass
{
protected static void Method<T>() where T : AbstractClass
{
Type t = typeof (T);
}
}
public class CurrentClass : AbstractClass
{
public void DoStuff()
{
Method<CurrentClass>(); // Here I'm calling it
}
}
You can gain access to the derived type from the static method simply by passing the type as a generic type argument to the base class.
I think you will have to either pass it in like the other suggestion or create a stack frame, I believe if you put an entire stack trace together though it can be expensive.
See http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
if you are calling this static method only from derived classes you can use 'System.Diagnostics.StackTrace' like
abstract class A
{
public abstract string F();
protected static string S()
{
var st = new StackTrace();
// this is what you are asking for
var callingType = st.GetFrame(1).GetMethod().DeclaringType;
return callingType.Name;
}
}
class B : A
{
public override string F()
{
return S(); // returns "B"
}
}
class C : A
{
public override string F()
{
return S(); // returns "C"
}
}
The method can't be static if you're going to call it without passing in a type. You can do this:
public abstract class AbstractClass {
protected void Method() {
var t = GetType(); // it's CurrentClass
}
}
If you also need it to be accessible from a static context, you can add an overload, even a generic overload, e.g.:
public abstract class AbstractClass {
protected static void Method<T>() {
Method(typeof(T));
}
protected static void Method(Type t) {
// put your logic here
}
protected void Method() {
Method(GetType());
}
}