vendredi 8 juillet 2016

Setting ReadOnly Strings without Reflection

I'm working on an application that requires access to public strings. However, I also wish to restrict write access. Since I have many strings, I want to avoid having a getter and private setter for each.

See code below:

public readonly string privateMem, peakVM, peakPaged, pagedSysMem, pagedMem, nonpagedSysMem;

    public override void Capture()
    {
        using (Process p = Process.GetCurrentProcess())
        {

            // Throws error as privateMem can't be assigned a value

            privateMem = string.Format("{0:N0} K", p.PrivateMemorySize64 / 1024);
            peakVM = string.Format("{0:N0} K", p.PeakVirtualMemorySize64 / 1024);
            peakPaged = string.Format("{0:N0} K", p.PeakPagedMemorySize64 / 1024);
            pagedSysMem = string.Format("{0:N0} K", p.PagedSystemMemorySize64 / 1024);
            pagedMem = string.Format("{0:N0} K", p.PagedMemorySize64 / 1024);
            nonpagedSysMem = string.Format("{0:N0} K", p.NonpagedSystemMemorySize64 / 1024);
        }

    }    

I know there are ways to assign a value to readonly fields with reflection, however I've gathered from several other stackoverflow questions that this is a terrible idea.

So in conclusion:

1. How can I assign a value to readonly strings without reflection, or does a better solution exist without using verbose getters and setters?

2. Is there a way to declare a variable, assign it a value, and then designate it as readonly?





Aucun commentaire:

Enregistrer un commentaire