是否有可能为const使用getter方法? [英] Is it possible to have a getter for a const?

查看:54
本文介绍了是否有可能为const使用getter方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是好奇,有没有办法让常量的吸气剂起作用?我有一个内部版本号,以确保库的两个版本仍然使用相同的语言,但是我希望程序员能够检查他们正在使用的版本.现在我用:

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

但是如果有办法的话,我宁愿只用const来做.

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

推荐答案

您可以仅使用get访问器声明属性(甚至不声明set访问器,甚至不声明私有访问器):

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

然后,将protocol_version修改为2,并仅重新编译类库,而无需重新编译程序,然后将新的类库放入程序文件夹并执行.您将看到:

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.

我认为您真正在寻找的是一个 static readonly 变量:这样,您将避免编译时const替换,并且该变量在初始化后将不可修改:

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;

这篇关于是否有可能为const使用getter方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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