Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.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# 如何实现子类中必须覆盖.net 4的常量字段_C#_Oop_C# 4.0 - Fatal编程技术网

C# 如何实现子类中必须覆盖.net 4的常量字段

C# 如何实现子类中必须覆盖.net 4的常量字段,c#,oop,c#-4.0,C#,Oop,C# 4.0,如何实现子类中必须覆盖的常量字段,我正在使用.net4,C 因为我有很多类,它们都有一个常量字段(具有不同的值),称为“pName” 所以我想使用一个接口或抽象类或某些东西作为父类,并强制这些类重写它 您请求的常量字段是矛盾的:您无法定义可以重写的常量值,因此在派生类中进行更改 您可以做的是在基类中定义默认值,并在派生类中重写它 public class Base { public static reaondly int DEFAULT_BASE_VALUE = 0, priv

如何实现子类中必须覆盖的
常量字段
,我正在使用
.net4,C

因为我有很多类,它们
都有一个常量字段
(具有不同的值),称为“pName”

所以我想使用一个接口或抽象类或某些东西作为父类,并强制这些类重写它


您请求的
常量
字段

是矛盾的:您无法定义可以重写的常量值,因此在派生类中进行更改

您可以做的是在基类中定义默认值,并在派生类中重写它

public class Base 
{
    public static reaondly int DEFAULT_BASE_VALUE = 0,
    private int _someValue = DEFAULT_BASE_VALUE;   //ASSIGN DEFAULT VALUE

    public virtual int SomeValue {
        get {
           return _someValue;
        }
    } 
}

public class Derived : Base
{

     public override int SomeValue {
        get {
           return -3;    //CHANGE VALUE OF BASE CLASS 
        }
    } 
}

不能,常量不是虚拟成员

你可以改为拥有一个只读属性,例如

public class BaseClass
{
    public BaseClass()
    {
    }

    protected int MyProperty { get { return 10; } }
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
    }

    protected override int MyProperty { get { return 20; } }
}

您不能
覆盖
a
const
;也不能将其声明为
静态
覆盖
它。您可以做的是重新声明它,但是不是健壮的——因为使用哪个版本取决于您请求的版本(完全在编译时-与多态性完全无关):

我建议您使用
虚拟
抽象
属性:

public virtual int Foo { get { return 4; } } // subclasses *can* override
public abstract int Foo { get; } // subclasses *must* override
覆盖

public override int Foo { get { return 12; } }

你不能。您可以这样声明一个抽象的只读属性

abstract class A
{
        public abstract int ReadOnlyProp {get;}
}

class B : A
{
    public override int ReadOnlyProp
    {
        get { return 42; }
    }
}

不清楚要覆盖什么。Readonly是Readonly:子类无法更改值-您必须将其作为
public-DerivedClass():base(20){}
或similar@MarcGravell糟糕,我的意思是把这个例子更新为虚拟财产。
abstract class A
{
        public abstract int ReadOnlyProp {get;}
}

class B : A
{
    public override int ReadOnlyProp
    {
        get { return 42; }
    }
}