I wonder if this is possible at all in C#:
ClassA c = new ClassB();
I get it why the right part has to have the class name, but then the left part doesn't have to have the class name ( var c = new Anything()
), so my guess is that it may be possible to create an instance of some class in this unusual way by explicitly typing the names of different (probably connected somehow) classes on the left and right of this expression. Am I wrong?
Well you could have something like
public interface ITADA
{
}
public class BaseTADA : ITADA
{
}
public class TADA : BaseTADA
{
}
and then
ITADA t1 = new TADA();
BaseTADA t2 = new TADA();
TADA t3 = new TADA();
This also allows you to do
List<ITADA> list = new List<ITADA>()
{
new TADA(),
new BaseTADA()
};
You should have a look at
It's even possible through operator overloading:
class A
{
}
class B
{
public static implicit operator A(B b)
{
return new A();
}
}
A a = new B();
or
class A
{
public static implicit operator A(B b)
{
return new A();
}
}
class B
{
}
A a = new B();
They are implicit conversions .
Note that they aren't connected to polymorphism. They are totally separate (orthogonal, not opposite!)
Purpose of declaring it that way is the same as declaring it with
ISomeInterface x=new ClassThatImplementsSomeInterface();
and that is to hide everything extra that new class has to offer and 'talk' to the object instance only using interface methods.
Your ClassA
needs to be base of ClassB
.
Edit:
Most of the literature will tell you that derivation can be, in English, told and written down as IS , as in:
ClassB *IS* ClassA
ClassThatImplementsSomeInterface *IS* ISomeInterface
in this manner, your declaration/assignment is completely correct.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.