How can i return data that is in base class form?
A aclass = new A();
B bclass = aclass.GetB();
does not work.
public class B
{
protected string str1;
protected string str2;
}
public class A:B
{
public A()
{
base.str1 = "A";
base.str2 = "B";
}
public B GetB()
{
return base;
}
}
GetB()
is completely unnecessary. B bclass = aclass;
is sufficient as aclass
is already a B
.
I'm no C# expert, but return this;
should work. I really don't see the point in doing this though.
I strongy advise not to use the following code and instead change the behavior of your class but the answer is the following:
public B GetB()
{
return this as B;
}
but instead writing a unique method for returning the object casted to the base class you may use the following;
public class B
{
protected string str1;
protected string str2;
}
public class A : B
{
public A()
{
str1 = "A";
str2 = "B";
}
}
and you can use as the following;
A a = new A();
B b = a;
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.