只是为了演示如何使用iterator method 非常简单地做到这一点...
public static IEnumerable<long> GetConstantsAsEnumerable()
{
yield return poperty1;
yield return poperty2;
yield return poperty3;
}
...或array initializer...
public static long[] GetConstantsAsArray()
{
return new long[] {
poperty1,
poperty2,
poperty3
};
}
当然,取决于N 的大小,任何一种方法都可能会增长很长时间。与 @TheGeneral's answer 不同,添加或删除常量时,您还必须手动更新方法以反映更改。
另外,对于@maccettura's point,如果这些编号的常量是相关的,并且您想以类似集合的方式访问它们,最好首先将它们存储为集合。你可以使用一个数组...
public static class SubClass
{
public static readonly long[] properties = new long[] { 365635, 156346, 280847 };
}
...或者,为了确保元素永远不会被修改,ReadOnlyCollection<>...
using System.Collections.ObjectModel;
public static class SubClass
{
public static readonly ReadOnlyCollection<long> properties =
new ReadOnlyCollection<long>(
new long[] { 365635, 156346, 280847 }
);
}
如果值是唯一的并且排序不重要,HashSet<> 可能是合适的...
using System.Collections.Generic;
public static class SubClass
{
public static readonly HashSet<long> properties = new HashSet<long>(
new long[] { 365635, 156346, 280847 }
);
}
...如果您使用的是 .NET Core,并且再次希望确保集合永远不会被修改,您可以使用 ImmutableHashSet<>...
using System.Collections.Immutable;
public static class SubClass
{
public static readonly ImmutableHashSet<long> properties = ImmutableHashSet.Create<long>(
new long[] { 365635, 156346, 280847 }
);
}
上述所有类型都可以按原样枚举,无需包装方法。