7

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

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

但如果有办法,我宁愿只用 const 来做。

4

4 回答 4

16

您可以声明一个只有 get 访问器的属性(甚至不声明 set 访问器,甚至不声明私有):

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

这与仅定义常量不同:常量将在编译时解析,因此如果您更新库而不重新编译依赖程序,程序仍会看到“旧”值。考虑这个例子:

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

现在,第一次编译并执行程序。你会看见

Constant : 1
Getter : 1

然后修改protocol_version为2,只重新编译类库,不重新编译程序,然后把新的类库放到程序文件夹中执行。你会看见:

Constant : 1
Getter : 2

事实是,如果它只是一个常量,则该值会在编译时被替换。

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;
于 2012-04-28T09:21:06.477 回答
3

您必须牢记 getter/setter 存在的原因。就是控制对封装变量的访问,特别是控制一个变量是如何改变的,谁可以改变它。由于 const 仅设置一次并且在运行时保持只读状态,因此没有理由为其创建属性。将常量设置为 public 是完全可以接受的,因为它不是需要保护的私有变量。

如果你真的......真的想把它变成一个属性,那么只需将它定义为一个只读属性,完全跳过设置器:

public Int16 ProtocolVersion { get { return protocol_version; } }

但是我们很清楚,我会说通常你会拥有与属性具有相同编码风格的公共常量:

public const Int16 ProtocolVersion = 1
于 2012-04-28T09:16:52.157 回答
2

做就是了:

public const Int16 protocol_version = 1;

这将提供一个公共 getter,因为它const不能有一个 setter。

于 2012-04-28T09:07:47.853 回答
0

常量不能被重新分配,因此为什么它们被称为常量,因此只需制作 protocol_versionpublic

private const Int16 protocol_version = 1;
于 2012-04-28T09:19:37.927 回答