Assigning to static readonly field of base class

喜你入骨 提交于 2019-12-01 03:26:57

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

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"; } }
}

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.

In your example, only a single field will exist, that of the base class and you can't have different values in a single field. Beside that, you can only initialize readonly fields in the same class, not in derived classes. A workaround could be defining a generic class like:

static class ProcessNames<T> {
   public static string Value { get; set; }
}

and use ProcessNames<DerivedClassType>.Value instead. Obviously, the value will be publicly accessible this way.

However, you should see if defining the field in each derived class separately fits your need and only resort to workarounds if it does not.

There's many ways to skin the cat. Here's another way you can do it.

public class ClassA
{
    public string ProcessName{ get; private set;}

    public ClassA()
    {
        ProcessName = "ClassAProcess";
    }

    public ClassA(string processName)
    {
        ProcessName = processName;
    }
}

public class ClassB : ClassA
{
    public ClassB() : base("ClassAProcess")
    {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!