如何使用摘要class的属性?
How to use an abstract class's property?
属性 在抽象 class 中,然后从 main 中调用。目标是打印 "Bip bip Digital" 但它只打印 "Bip bip"。我什至尝试使用构造函数设置 _phoneType 变量,但它也不起作用。
using System;
abstract class Telephone
{
protected string _phoneType;
public string PhoneType {
set
{
_phoneType = PhoneType;
}
get
{
return _phoneType;
}
}
public abstract void Ring();
}
class DigitalPhone : Telephone
{
public override void Ring()
{
Console.WriteLine("Bip bip {0}", _phoneType);
}
}
class Program
{
static void Main()
{
DigitalPhone myDPhone = new DigitalPhone();
myDPhone.PhoneType = "Digital";
myDPhone.Ring();
}
}
setter 有问题,它没有将传入的值设置为 _phoneType。容易犯的错误。应该是...
set
{
_phoneType = value;
}
否则代码对我来说都很好。
您的 PhoneType
setter 目前只是将 _phoneType
设置为其当前值,最初为空。您应该将其更改为:
set
{
_phoneType = value;
}
或简单地使用 auto-property:
public string PhoneType { get; set; }
属性 在抽象 class 中,然后从 main 中调用。目标是打印 "Bip bip Digital" 但它只打印 "Bip bip"。我什至尝试使用构造函数设置 _phoneType 变量,但它也不起作用。
using System;
abstract class Telephone
{
protected string _phoneType;
public string PhoneType {
set
{
_phoneType = PhoneType;
}
get
{
return _phoneType;
}
}
public abstract void Ring();
}
class DigitalPhone : Telephone
{
public override void Ring()
{
Console.WriteLine("Bip bip {0}", _phoneType);
}
}
class Program
{
static void Main()
{
DigitalPhone myDPhone = new DigitalPhone();
myDPhone.PhoneType = "Digital";
myDPhone.Ring();
}
}
setter 有问题,它没有将传入的值设置为 _phoneType。容易犯的错误。应该是...
set
{
_phoneType = value;
}
否则代码对我来说都很好。
您的 PhoneType
setter 目前只是将 _phoneType
设置为其当前值,最初为空。您应该将其更改为:
set
{
_phoneType = value;
}
或简单地使用 auto-property:
public string PhoneType { get; set; }