如何设置BASE CLASS值 [英] How to Set BASE CLASS with value

查看:71
本文介绍了如何设置BASE CLASS值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨专家,



我有一个类OLDCar,其中有一些属性和方法,我无法在这里更改和创建方法。

所以我需要创建一个NEWCAR类,基类是OLDCar。然后如何在clild类中设置基类的值。





class OLDCAR

{}



class NewCar:OLDCAR

{

public isAirbag {get; set;}

}





旧车有一些价值,那我怎样才能传递新车对象的价值..

Hi Experts,

I have a class OLDCar in which have some properties and methods and i have not access to change and create methods here.
So i need to create a NEWCAR Class there base class is OLDCar. then how can i set the value of base class in clild class.


class OLDCAR
{}

class NewCar :OLDCAR
{
public isAirbag {get;set;}
}


Old car having some values then how can i pass the value in new car object..

推荐答案

向patel_vijay道歉以扩展他的解决方案...

With apologies to patel_vijay for expanding on his solution ...
引用:

或者你可以使用this或base关键字在deried类中访问基类属性。

Or you can acess the base class properties in deried class using this or base keyword.

这里有一个例子......

假设你有类似

here is an example...
Say you have something set up like

public class OldCar
{
    protected int aHiddenProp;
    public int AHiddenProp
    {
      get { return aHiddenProp; }
      set { aHiddenProp = value; }
    }
}
public class NewCar : OldCar
{
    // This class adds some stuff to OldCar e.g.
    private bool _isAirBag;
    public bool IsAirBag
    {
        get { return _isAirBag; }
        set { _isAirBag = value; }
    }
    public string showValues()
    {
        base.AHiddenProp = 4; // change the value in the base class
        return _isAirBag.ToString() + ' ' + base.AHiddenProp.ToString();
    }
}



然后创建NewCar类实例的任何东西都可以使用底层基类属性......


then anything creating an instance of the NewCar class can use the underlying base class properties as well...

private void button1_Click(object sender, EventArgs e)
{
    NewCar nc = new NewCar();
    nc.AHiddenProp = 3;         // this is actually in the base class
    nc.IsAirBag = true;
    MessageBox.Show(nc.showValues());
}



messageBox将显示True 4,因为我调整了showValues函数中的值





如果你(真的)想要将OldCar的实例传递给NewCar,那么你必须为NewCar编写一个合适的构造函数,例如


The messageBox will display "True 4" because I''ve adjusted the value in the showValues function


If you (really) want to pass an instance of OldCar to NewCar then you will have to write an appropriate constructor for NewCar e.g.

public NewCar() { }
public NewCar(OldCar oc)
{
    this.AHiddenProp = oc.AHiddenProp;
    // copy all of the values passed in oc to this instance
}





但更好的路线就是首先使用NewCar。



另请参阅 http://msdn.microsoft.com/en-us/library/ms173149.aspx [ ^ ]


如果你 OLDCLASS 类接受contructor中的参数,那么你可以传递如下值。

if you OLDCLASS class accepting parameters in contructor then you can pass values as below.
public NewCar(int param1)
            : base(param1)
        { }





或者您可以在deried中获取基类属性使用基本关键字。


这篇关于如何设置BASE CLASS值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆