为什么要使用受保护的变量(成员/属性)与继承?什么是使用它的优势是什么? [英] Why should I use protected variables(members/property) with Inheritance? What are the advantages of using it?

查看:128
本文介绍了为什么要使用受保护的变量(成员/属性)与继承?什么是使用它的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所经历的code的<一个样本href="http://www.wrox.com/WileyCDA/WroxTitle/Beginning-C-3-0-An-Introduction-to-Object-Oriented-Programming.productCd-0470261293.html"相对=nofollow>起始C#3.0 并随后将样品code沿。

当我创建了一个公用/受保护的方法,然后我能够访问使用派生类对象的方法。例如:

 类clsBuilding
    {
    保护字符串的地址{获得;组; }
    保护十进制进价{获得;组; }
    保护十进制monthlyPayment {获得;组; }
    保护十进制税{获得;组; }
    保护十进制保险{获得;组; }
    受保护的DateTime购置日期{获得;组; }
    保护INT buildingType {获得;组; }


     公共无效PropertySummary(字符串[] DESC)
        {
            说明[0] =属性类型:+ whichType [buildingType] +
                        ,+地址+
                        成本:+ purchasePrice.ToString(C)+
                        ,每月付款方式:+ monthlyPayment.ToString(C);
            说明[1] =保险+ insurance.ToString(C)+
                        税:+ taxes.ToString(C)+
                            购买日期:+ datePurchased.ToShortDateString();
            降序[2] =;
        }
..............
}

类clsApartment:clsBuilding
    {
      ........................
}
.......
myApt =新clsApartment();

myApt.PropertySummary(DESC);
 

但是,什么是使用受保护的财产,我在父类的开头宣布。当我试图通过派生类或对象或者访问它们直接作为指导书中:

  

只是来驱动点回家,鉴于clsBuilding(父类)的行:

 保护十进制货款;
 

你可以有行:

  

你可以有行进价= 150000M,在类的家,这将是完全可以接受的。 (第15章,第4段后447页),也不是一次成功的尝试。

我相信,肯定有我的概念错误,或错过了什么。如果没有的话,为什么任何人会保护声明变量或属性?

修改

 公共类clsBuilding
{
    // ---------------------符号常量-------------------
    公共const int的公寓= 1;
    公共const int的商业= 2;
    公共const int的HOME = 3;

    私人字符串[] whichType = {,公寓,商业,家};

    // ---------------------实例变量-------------------
    受保护的字符串地址;
    保护十进制进价;
    保护十进制monthlyPayment;
    保护十进制税;
    保护十进制保险;
    受保护的DateTime购置日期;
    保护INT buildingType;
    // ---------------------构造--------------------------
    公共clsBuilding()
    {
        地址=没有关闭;
    }

    公共clsBuilding(字符串的地址,十进制价格,小数付款,
                       十进制税,小数INSUR,日期时间日期,int型的):这个()
    {
        如果(addr.Equals()==假)
            地址=地址;
        进价=价格;
        monthlyPayment =支付;
        税费=税;
        保险= INSUR;
        购置日期=日期;
        buildingType =类型;
    }
    // ---------------------属性方法---------------------

    公共字符串地址
    {
        得到
        {
            退货地址;
        }
        组
        {
            如果(value.Length!= 0)
                地址=价值;
        }
    }
    公共小数进价
    {
        得到
        {
            返回进价;
        }
        组
        {
            如果(值GT; 0M)
                进价=价值;
        }
    }

    公共小数MonthlyPayment
    {
        得到
        {
            返回monthlyPayment;
        }
        组
        {
            如果(值GT; 0M)
                monthlyPayment =价值;
        }
    }

    公共小数税
    {
        得到
        {
            返回税;
        }
        组
        {
            如果(值GT; 0M)
                税费=价值;
        }
    }

    公共小数保险
    {
        得到
        {
            回归保险;
        }
        组
        {
            如果(值GT; 0M)
                保险=价值;
        }
    }

    公众的DateTime购置日期
    {
        得到
        {
            返回购置日期;
        }
        组
        {
            如果(value.Year&GT; 2008)
                购置日期=值;
        }
    }

    公众诠释BuildingType
    {
        得到
        {
            返回buildingType;
        }
        组
        {
            如果(值GT =公寓式放大器;&放大器;值小于= HOME)
                buildingType =价值;
        }
    }
    // ---------------------常规方法----------------------

    / *****
     *目的:提供属性的基本描述
     *
     *参数列表:
     *字符串[]递减一个字符串数组来保存说明
     *
     *返回值:
     *无效
     *
     *注意:方法假定有数组3个元素
     ****** /
    公共无效PropertySummary(字符串[] DESC)
    {

        说明[0] =房产类型:+ whichType [buildingType] +
                  ,+地址+
                  成本:+ purchasePrice.ToString(C)+
                  ,月付:+ monthlyPayment.ToString(C);
        说明[1] =保险+ insurance.ToString(C)+税:+ taxes.ToString(C)+
                  购买日期:+ datePurchased.ToShortDateString();
        降序[2] =;
    }

    / *****
     *目的:找专业除雪,如果有的话
     *
     *参数列表:
     * N / A
     *
     *返回值:
     *  串
     ****** /
    公共虚拟字符串RemoveSnow()
    {
        返回whichType [buildingType] +:无除雪服务可用。
    }
}

类clsCommercial:clsBuilding
{
    // ---------------------实例变量-------------------
    私人诠释squareFeet;
    私人诠释parkingSpaces;
    私人十进制rentPerSquareFoot;

    // ---------------------构造--------------------------
    公共clsCommercial(字符串的地址,十进制价格,小数付款,
                        十进制税,小数INSUR,日期时间日期,int型的):
                        基地(地址,价格,付款,税收,INSUR,日期,类型)
    {
        buildingType =类型; //从基地商用型
    }
    // ---------------------属性方法---------------------
    公众诠释SquareFeet
    {
        得到
        {
            返回squareFeet;
        }
        组
        {
            如果(值0)
                squareFeet =价值;
        }
    }
    公众诠释ParkingSpaces
    {
        得到
        {
            返回parkingSpaces;
        }
        组
        {
            parkingSpaces =价值;
        }
    }
    公共小数RentPerSquareFoot
    {
        得到
        {
            返回rentPerSquareFoot;
        }
        组
        {
            如果(值GT; 0M)
                rentPerSquareFoot =价值;
        }
    }

    // ---------------------常规方法----------------------
    公众覆盖字符串RemoveSnow()
    {
        返回商业:呼叫尖端清雪:803.234.5566;
    }

}


公共frmMain()
    {
        的InitializeComponent();
        数值指明MyTime = DateTime.Now;

        myApt =新clsApartment(123安Dotson博士,列克星敦40502,550000 6000,
                                             15000,3400,数值指明MyTime,1);
        myComm =新clsCommercial(4442帕克广场,纽约,SC 29745,120,9000,
                                        22000,8000,数值指明MyTime,2);
        MYHOME =新clsHome(657达拉斯圣,灵戈尔德,GA 30736,260000,1100,
                                    1750,900,数值指明MyTime,3);
    }
 

解决方案

建立在什么道格说。保护使一个属性,变量或提供给一个子类的功能,但不从类的外部。如果您是使用私有的,它仍然不能从类的外部访问,也不会从它的子类进行访问。

I was going through code samples of Begining C# 3.0 and followed the sample code along.

When I have created a public/protected method then I was able to access that method using the object of derived class. Ex:

class clsBuilding
    {
    protected string address { get; set; }
    protected Decimal purchasePrice { get; set; }
    protected decimal monthlyPayment { get; set; }
    protected Decimal taxes { get; set; }
    protected decimal insurance { get; set; }
    protected DateTime datePurchased { get; set; }
    protected int buildingType { get; set; }


     public void PropertySummary(string[] desc)
        {
            desc[0] = "Property Type:  "+whichType[buildingType] +
                        "," + address +
                        ",Cost: " + purchasePrice.ToString("C")+
                        ", Monthly Payment:" + monthlyPayment.ToString("C");
            desc[1] = "Insurance: " + insurance.ToString("C") +
                        " Taxes:  " + taxes.ToString("C")+
                            "Date Purchased: " + datePurchased.ToShortDateString();
            desc[2] = "";
        }
..............
}

class clsApartment : clsBuilding
    {
      ........................
}
.......
myApt = new clsApartment();

myApt.PropertySummary(desc);

But what is the use of protected property that I have declared at the begining of the parent Class. When I was trying to access them either by using the object of the derived class or directly as instructed in the book:

Just to Drive the point home,given a line in clsBuilding(parent class):

protected decimal purchase price;

you could have the line :

you could have the line purchaseprice = 150000M ; in class home and it would be perfectly acceptable. (Chapter 15,page 447 after 4th paragraph) , neither was a successful on attempt.

I am sure , I must have got the concept wrong or missed something. If not then , why any one would be declaring protected variable or property?

EDIT:

public class clsBuilding
{
    //--------------------- Symbolic constants -------------------
    public const int APARTMENT = 1;
    public const int COMMERCIAL = 2;
    public const int HOME = 3;

    private string[] whichType = { "", "Apartment", "Commercial", "Home" };

    //--------------------- Instance variables -------------------
    protected string address;
    protected decimal purchasePrice;
    protected decimal monthlyPayment;
    protected decimal taxes;
    protected decimal insurance;
    protected DateTime datePurchased;
    protected int buildingType;
    //--------------------- Constructor --------------------------
    public clsBuilding()
    {
        address = "Not closed yet";
    }

    public clsBuilding(string addr, decimal price, decimal payment,
                       decimal tax, decimal insur, DateTime date, int type):this()
    {
        if (addr.Equals("") == false)
            address = addr;
        purchasePrice = price;
        monthlyPayment = payment;
        taxes = tax;
        insurance = insur;
        datePurchased = date;
        buildingType = type;
    }
    //--------------------- Property Methods ---------------------

    public string Address
    {
        get
        {
            return address;
        }
        set
        {
            if (value.Length != 0)
                address = value;
        }
    }
    public decimal PurchasePrice
    {
        get
        {
            return purchasePrice;
        }
        set
        {
            if (value > 0M)
                purchasePrice = value;
        }
    }

    public decimal MonthlyPayment
    {
        get
        {
            return monthlyPayment;
        }
        set
        {
            if (value > 0M)
                monthlyPayment = value;
        }
    }

    public decimal Taxes
    {
        get
        {
            return taxes;
        }
        set
        {
            if (value > 0M)
                taxes = value;
        }
    }

    public decimal Insurance
    {
        get
        {
            return insurance;
        }
        set
        {
            if (value > 0M)
                insurance = value;
        }
    }

    public DateTime DatePurchased
    {
        get
        {
            return datePurchased;
        }
        set
        {
            if (value.Year > 2008)
                datePurchased = value;
        }
    }

    public int BuildingType
    {
        get
        {
            return buildingType;
        }
        set
        {
            if (value >= APARTMENT && value <= HOME)
                buildingType = value;
        }
    }
    //--------------------- General Methods ----------------------

    /*****
     * Purpose: Provide a basic description of the property
     * 
     * Parameter list:
     *  string[] desc       a string array to hold description
     *  
     * Return value:
     *  void
     *  
     * CAUTION: Method assumes that there are 3 elements in array
     ******/
    public void PropertySummary(string[] desc)
    {

        desc[0] = "Property type: " + whichType[buildingType] + 
                  ", " + address + 
                  ", Cost: " + purchasePrice.ToString("C") + 
                  ", Monthly payment: " + monthlyPayment.ToString("C");
        desc[1] = "     Insurance: " + insurance.ToString("C") + " Taxes: " + taxes.ToString("C") + 
                  "  Date purchased: " + datePurchased.ToShortDateString();
        desc[2] = " ";
    }

    /*****
     * Purpose: To call someone for snow removal, if available
     * 
     * Parameter list:
     *  n/a
     *  
     * Return value:
     *  string
     ******/
    public virtual string RemoveSnow()
    {
        return whichType[buildingType] + ": No snow removal service available.";
    }
}

class clsCommercial : clsBuilding
{
    //--------------------- Instance variables -------------------
    private int squareFeet;
    private int parkingSpaces;
    private decimal rentPerSquareFoot;

    //--------------------- Constructor --------------------------
    public clsCommercial(string addr, decimal price, decimal payment,
                        decimal tax, decimal insur, DateTime date, int type) :
                        base(addr, price, payment, tax, insur, date, type)
    {
        buildingType = type;   // Commercial type from base
    }
    //--------------------- Property Methods ---------------------
    public int SquareFeet
    {
        get
        {
            return squareFeet;
        }
        set
        {
            if (value > 0)
                squareFeet = value;
        }
    }
    public int ParkingSpaces
    {
        get
        {
            return parkingSpaces;
        }
        set
        {
            parkingSpaces = value;
        }
    }
    public decimal RentPerSquareFoot
    {
        get
        {
            return rentPerSquareFoot;
        }
        set
        {
            if (value > 0M)
                rentPerSquareFoot = value;
        }
    }

    //--------------------- General Methods ----------------------
    public override string RemoveSnow()
    {
        return "Commercial: Call Acme Snow Plowing: 803.234.5566";
    }

}


public frmMain()
    {
        InitializeComponent();
        myTime = DateTime.Now;

        myApt = new clsApartment("123 Ann Dotson Dr., Lexington, KY 40502", 550000, 6000,
                                             15000, 3400, myTime, 1);
        myComm = new clsCommercial("4442 Parker Place, York, SC 29745", 1200000, 9000,
                                        22000, 8000, myTime, 2);
        myHome = new clsHome("657 Dallas St, Ringgold, GA 30736", 260000, 1100,
                                    1750, 900, myTime, 3);
    }

解决方案

Building on what doug said. Protected makes a property, variable, or function available to a subclass, but not from outside the class. If you were to use private, it would still not be accessible from outside the class, nor would it be accessible from it's subclasses.

这篇关于为什么要使用受保护的变量(成员/属性)与继承?什么是使用它的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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