鉴于此代码:
public static class SubClass
{
public const long poperty1 = 365635;
public const long poperty2 = 156346;
public const long poperty3 = 280847;
.
.
public const long propertyN = 29145;
}
具有N个长属性的类。是否可以添加一个方法来返回包含所有属性值的IEnumerable?
只是为了演示如何使用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 }
);
}
所有上述类型都可以按原样枚举,不需要包装器方法。
是否可以添加一个方法来返回包含所有属性值的IEnumerable?
您可以使用它,它将从静态类中选择所有公共常量长字段
var result = typeof(SubClass).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(x=> x.IsLiteral && !x.IsInitOnly && x.FieldType == typeof(long))
.Select(x => x.GetRawConstantValue());
您可以按如下方式阅读
用于获取类型的System.Type对象。 typeof表达式采用以下形式:
获取当前Type的字段。
Public指定要将公共成员包含在搜索中。
静态指定静态成员将包含在搜索中。
哪个回报
发现字段的属性并提供对字段元数据的访问。
过滤(Where)
获取一个值,该值指示值是否在编译时写入且无法更改。
获取一个值,该值指示是否只能在构造函数的主体中设置该字段。
然后选择
FieldInfo.GetRawConstantValue Method
返回编译器与字段关联的文字值。