Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

c# - Is it possible to have a getter for a const?

Just curious, is there a way to have a getter for a constant variable? I have a sort of internal version number to ensure that two versions of a library are still speaking the same language, but I'd like the programmer to be able to check what version they're using. Right now I use:

 private const Int16 protocol_version = 1;
 public Int16 ProtocolVersion { get { return protocol_version; } }

But I'd prefer to do it with just the const if there's a way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could declare a property with only a get accessor (without even declaring the set accessor, not even private):

private const Int16 protocol_version = 1;
public Int16 ProtocolVersion { 
    get { return protocol_version; } 
}

This is not the same as defining a constant only: the constant would be resolved at compile time, so if you update the library without recompiling the dependent program, the program would still see the "old" value. Consider this example:

// The class library
using System;

namespace MyClassLibrary {
    public class X {
        public const Int16 protocol_version = 1;
        public Int16 ProtocolVersion { get { return protocol_version; } }
    }
}

// The program
using System;
using MyClassLibrary;

class Program {
    static void Main(string[] args) {
        X x = new X();
        Console.WriteLine("Constant : {0}", X.protocol_version);
        Console.WriteLine("Getter: {0}", x.ProtocolVersion);
    }
}

Now, compile the first time and execute the program. You will see

Constant : 1
Getter : 1

Then, modify protocol_version to 2, and recompile the class library only, without recompiling the program, then put the new class library in the program folder and execute it. You will see:

Constant : 1
Getter : 2

The fact is that if it's just a constant, the value is replaced at compile time.

I think that what you are actually looking for is a static readonly variable: in that way, you will avoid the compile-time const replacement, and the variable will not be modifiable after initialization:

public static readonly Int16 protocol_version = 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...