是否有可能获得const的getter?
只是好奇,有没有办法让恒定变量的吸气剂? 我有一种内部版本号,以确保两个版本的库仍然使用相同的语言,但我希望程序员能够检查他们使用的是什么版本。 现在我使用:
private const Int16 protocol_version = 1; public Int16 ProtocolVersion { get { return protocol_version; } }
但如果有办法,我宁愿只用const来做。
你可以声明一个只有一个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
事实是,如果它只是一个常量,则在编译时替换该值。
我认为您实际需要的是一个static readonly
变量:这样,您将避免编译时const替换,并且该变量在初始化后将无法修改:
public static readonly Int16 protocol_version = 1;
你必须记住存在getter / setter的原因。 它是控制对封装变量的访问,特别是控制变量的更改方式以及谁可以更改变量。 由于const只设置一次并且在运行时保持只读,因此没有理由为它创建属性。 将常量设置为public是完全可以接受的,因为它不是需要保护的私有变量。
如果你真的…真的想让它成为一个属性,那么只需将它定义为只读属性,完全跳过setter:
public Int16 ProtocolVersion { get { return protocol_version; } }
但是我们很清楚,我会说通常你会使用与属性相同的编码风格的公共常量:
public const Int16 ProtocolVersion = 1
做就是了:
public const Int16 protocol_version = 1;
这将提供一个公共getter,因为const
不能有setter。
常量不能被重新分配,因此它们被称为常量,因此只需将protocol_version public
private const Int16 protocol_version = 1;
- 施放然后检查或检查然后施放?
- 在XAML中使用boolean到颜色转换器
- 使用WindowsImpersonationContext模拟当前用户访问网络驱动器
- 在SSH隧道中创建转发端口
- ASP.Net Identity 2.0 AccessFailedCount不递增
- ‘AspNetUser’类型的属性’Claims’不是导航属性
- Async / Await等同于.ContinueWith和CancellationToken以及TaskScheduler.FromCurrentSynchronizationContext()调度程序
- 如何使用WinForms(.NET)绘制圆角矩形?
- 了解多项目(可互操作).NET解决方案中的配置文件