问题
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;
}
}
回答1:
GetB() is completely unnecessary. B bclass = aclass; is sufficient as aclass is already a B.
回答2:
I'm no C# expert, but return this; should work. I really don't see the point in doing this though.
回答3:
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;
来源:https://stackoverflow.com/questions/14482799/return-base-class-in-c-sharp