Return base class in C#

别说谁变了你拦得住时间么 提交于 2019-12-13 04:16:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!