I'll give an example, so you can better understand what i mean:
public class Base
{
public Base Common()
{
return this;
}
}
public class XBase : Base
{
public XBase XMethod()
{
return this;
}
}
I want to be able to do something like:
var a = new XBase().Common().XMethod();
but this is not possible as Common()
returns Base
, and XMethod()
is not defined in Base
.
Is there any possible way i could acomplish this ?
I'm asking because i have a BaseComponent
, and a lot of other Components
that inherit this class, and i have to declare the common methods in each one, just to call base.Method()
inside.
Thanks for your help.
PS: without using generics and specifying the child's type:
var a = new XBase().Common<XBase>().XMethod();
You could make Base
generic and use the Curiously Repeating Template Pattern:
public class Base<T> where T : Base<T>
{
public T Common()
{
return (T)this;
}
}
public class XBase : Base<XBase>
{
public XBase XMethod()
{
return this;
}
}
Then you can just use:
var a = new XBase().Common().XMethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With