Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重写派生类(c#)中的默认值_C#_Default_Overriding - Fatal编程技术网

重写派生类(c#)中的默认值

重写派生类(c#)中的默认值,c#,default,overriding,C#,Default,Overriding,如果基类中有访问器和默认属性,如下所示: class base{ protected int _foo = 5; public int foo {get{return _foo;}set{_foo = value;}} } 然后我派生这个类,是否可以覆盖_foo的默认值 class derived:base{ // foo still returns 5? protected new int _foo = 10; } \u foo=5语句在基类的构造函数中有效执行。您可以将代码添加到派生类构

如果基类中有访问器和默认属性,如下所示:

class base{
protected int _foo = 5;
public int foo {get{return _foo;}set{_foo = value;}}
}
然后我派生这个类,是否可以覆盖_foo的默认值

class derived:base{
// foo still returns 5?
protected new int _foo = 10;
}

\u foo=5
语句在基类的构造函数中有效执行。您可以将代码添加到派生类构造函数中,然后立即更改
foo
的值:

class derived:base{
    public derived()
    {
        foo = 10;
    }
}

您可以创建一个属性:

protected virtual int _foo { get { return 5; } }
class derived:base
{
    public derived()
    {
        this._foo = 10;
    }
}


您可以使用构造函数初始化派生类并设置基类型\u foo属性:

protected virtual int _foo { get { return 5; } }
class derived:base
{
    public derived()
    {
        this._foo = 10;
    }
}

您的代码格式有点奇怪:.NET代码对类和类成员使用PascalCase(即
Base
Derived
Foo
)。你应该知道,这不是一个常数。不建议在构造函数中调用虚拟属性(例如初始化变量),因为会产生副作用,CA会抱怨(基类未初始化时调用派生代码)。这很好,但我不能再为“foo”赋值了。它不是默认值,它更像是固定值,因为当你设定值时,你将永远无法得到它