gpt4 book ai didi

c# - 从静态类返回特定类型的常量字段值数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:58 25 4
gpt4 key购买 nike

给定这段代码:

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 个 long 属性的类。是否可以添加一个方法来返回具有所有属性值的 IEnumerable?

最佳答案

Is possible to add a method to return an IEnumerable with all the properties values?

你可以使用它,它将从静态类中选择所有公共(public)常量长字段

var result = typeof(SubClass).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(x=> x.IsLiteral && !x.IsInitOnly && x.FieldType == typeof(long))
.Select(x => x.GetRawConstantValue());

阅读方式如下

typeof (C# Reference)

Used to obtain the System.Type object for a type. A typeof expression takes the following form:

Type.GetFields Method

Gets the fields of the current Type.

BindingFlags Enum

Public Specifies that public members are to be included in the search.

Static Specifies that static members are to be included in the search.

哪个返回

FieldInfo Class

Discovers the attributes of a field and provides access to field metadata.

按(位置)过滤

FieldInfo.IsLiteral Property

Gets a value indicating whether the value is written at compile time and cannot be changed.

FieldInfo.IsInitOnly Property

Gets a value indicating whether the field can only be set in the body of the constructor.

然后选择

FieldInfo.GetRawConstantValue Method

Returns a literal value associated with the field by a compiler.

关于c# - 从静态类返回特定类型的常量字段值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52193208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com