请考虑以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class BaseClass
{
public virtual void DoWork() { Console.WriteLine("BaseClass\n"); }
public virtual int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public override void DoWork() { Console.WriteLine("DerivedClass\n"); }
public override int WorkProperty
{
get { return 1; }
}
}
如何使用WorkProperty
?坦白说,它似乎毫无用处。
主要:
class Program
{
static void Main(string[] args)
{
BaseClass A2 = new DerivedClass();
int a = A2.WorkProperty;
Console.WriteLine(a);
// do more stuff with `a`
}
}
另一方面,如果我有这样的事情:
public class CoOrds
{
private int x, y;
public CoOrds() // constructor
{
x = 0;
y = 0;
}
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
get { return y; }
set { y = value; }
}
}
然后x
和y
是数据成员,这里的属性很有帮助。
那么第一个代码中属性的目的是什么?
感谢名单
答案 0 :(得分:3)
如果您使属性有意义,则在覆盖它们时更有意义。虚拟属性提供了一个默认子类,当子类有意义覆盖它们时,它们可以覆盖它们。请参阅此PsudoStream类示例。
class PsudoStream
{
public virtual bool CanRead { get { return false; } }
public virtual bool CanWrite { get { return false; } }
}
class WritableStream : PsudoStream
{
//CanRead is false already and does not need to be overwritten
public override bool CanWrite { get { return true; } }
}
class ReadableStream : PsudoStream
{
//CanWrite is false already and does not need to be overwritten
public override bool CanRead { get { return true; } }
}
答案 1 :(得分:0)
那么第一个代码中属性的目的是什么?
在baseClass中给出WorkProperty
的目的是,如果derivedClass都没有覆盖该属性,它将作为默认属性。
例如考虑这段代码,
public class BaseClass
{
public virtual void DoWork() { Console.WriteLine("BaseClass\n"); }
public virtual int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public override void DoWork() { Console.WriteLine("DerivedClass\n"); }
}
class Program
{
static void Main(string[] args)
{
BaseClass A2 = new DerivedClass();
int a = A2.WorkProperty;
Console.WriteLine(a); ***//output will be "0"***
// do more stuff with `a`
}
}
此处输出为“0”,因为它使用了baseClass中的Defauklt WorkProperty,因为没有找到重写的实现。