分配给基类的静态只读字段 [英] Assigning to static readonly field of base class

查看:54
本文介绍了分配给基类的静态只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class ClassA
{
    public static readonly string processName;
} 

public class ClassB : ClassA
{
    static ClassB()
    {
        processName = "MyProcess.exe";
    }
}

在编译上面的C#代码时出现错误.

I am getting an error while compiling the above C# code.

错误提示-无法将静态只读字段分配给它(除了在静态构造函数或变量初始化程序中)"

The error says -- "A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)"

但是我是在静态构造函数中分配它的.

But I am assigning it in a static constructor.

对这样一个静态变量的需要是,基类具有使用此变量的方法,但是派生类和基类必须对此变量具有不同的值.但是该值在各个类的所有实例中都是恒定的.它必须是只读的,因为它不能在任何地方更改.

The need for such a static variable is that, the base class has methods that uses this variable, but the derived classes and the base class must have different values for this variable. But the value is constant across all instances of the respective class. It must be readonly because, it must not be changed by anywhere.

上面的代码有什么错误?(如果有的话)我似乎找不到.该错误信息无济于事.因为我没有做错任何事情.

What is the error in the above code? (If there is any) I do not seem to be able to spot one. The error message is not helping. As I am not doing anything wrong according to it.

如果出现错误,如何实现此功能?我知道一个简单的解决方法是将其设置为实例变量,并在派生类中为其分配不同的值.但这是不必要的,因为该值在各个类的所有实例中都是恒定的.

If there is an error, how can I implement this functionality? I know a simple workaround would be to make it an instance variable and assign them different values in the derived classes. But that is unnecessary as the value is constant across all the instances of the respective class.

推荐答案

不过,您是在错误静态构造函数中进行分配的.只能在声明变量的类型的静态构造函数中分配它.

You're assigning in the wrong static constructor though. It can only be assigned in a static constructor for the type declaring the variable.

假设您有另一个类是从ClassC派生的,该类也做同样的事情-您最终将覆盖该变量,该变量是只读的.这里有一个单个静态变量,但是您拥有许多派生类.

Suppose you have another class deriving from ClassC which does the same thing - you'd end up overwriting the variable, which is meant to be readonly. There's a single static variable here, however many derived classes you've got.

一个答案是避免使用静态的变量,而是在基类中放置虚拟的属性,并使每个派生的类重写该属性以返回不同的常量:

One answer is to avoid using a static variable but put a virtual property in the base class, and make each derived class override the property to return a different constant:

public class ClassA
{
    public virtual string ProcessName { get { return "ClassAProcess"; } }
} 

public class ClassB : ClassA
{
    public override string ProcessName { get { return "MyProcess.exe"; } }
}

基本上,选择是将静态"位分隔为单独的层次结构-实际上,这听起来像是您希望类型而不是实例具有多态性,而.NET不支持这种方式.

Basically option would be to separate the "static" bits into a separate hierarchy - effectively it sounds like you want polymorphism over the type instead of instances, and that isn't supported in .NET.

这篇关于分配给基类的静态只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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