我有第三方结构,包含以下内容:
[StructLayout(LayoutKind.Sequential, Size=1)]
public struct BigBlueReasonCodes
{
public const int ABC_REASONCODE_DESCRIPTION001 = 1000;
public const int ABC_REASONCODE_DESCRIPTION002 = 1005;
public const int ABC_REASONCODE_DESCRIPTION003 = 1010;
public const int DEF_REASONCODE_DESCRIPTION004 = 2001;
public const int DEF_REASONCODE_DESCRIPTION005 = 2010;
public const int DEF_REASONCODE_DESCRIPTION006 = 2013;
public const int GHI_REASONCODE_DESCRIPTION007 = 3050;
public const int GHI_REASONCODE_DESCRIPTION008 = 3050;
public const int GHI_REASONCODE_DESCRIPTION009 = 3052;
public const string JKL_REASONCODE_DESCRIPTION010 = "XYZ";
public const string GHI_REASONCODE_DESCRIPTION011 = "ST";
static BigblueReasonCodes();
}
我正在尝试根据原因代码(值)查找原因描述(字段名称),以便我的课程可以像:
string failureReason = GetReasonDescription(reasoncode);
提到的一些事情是一些有int值,一些有字符串值。 我只担心具有int值的那些。 我也只想要那些以GHI_开头的,如果可能的话,但没什么大不了的。
答案 0 :(得分:6)
你可以通过分析结构来解决它:
public string GetReasonDescription(int reasonCode)
{
return
typeof(BigBlueReasonCodes)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(field => field.FieldType == typeof(int)) // Filter int values
.Where(field => field.Name.StartsWith("GHI"))
.Where(field => (int) field.GetValue(null) == reasonCode)
.Select(field => field.Name).First(); // Assuming a field must exists
}
用法示例:
[Test]
public void GetReasonDescriptionTest()
{
string reasonDescription = GetReasonDescription(3050);
Assert.That(reasonDescription, Is.EqualTo("GHI_REASONCODE_DESCRIPTION007"));
}
答案 1 :(得分:4)
看起来你的整数consts应该是enumeration(或几个枚举) - 这也允许转换为整数和从整数转换。
你可以通过反射来做到这一点,但它比转换为枚举要慢。
答案 2 :(得分:1)
如果将整数值填充到枚举而不是常量中,则可以执行
public enum BigBlueReasonCode
{
ABC_REASONCODE_DESCRIPTION01 = 1000,
ABC_REASONCODE_DESCRIPTION01 = 1005,
ABC_REASONCODE_DESCRIPTION01 = 1010,
DEF_REASONCODE_DESCRIPTION01 = 2001,
DEF_REASONCODE_DESCRIPTION01 = 2010,
DEF_REASONCODE_DESCRIPTION01 = 2013,
GHI_REASONCODE_DESCRIPTION01 = 3050,
GHI_REASONCODE_DESCRIPTION01 = 3051,
GHI_REASONCODE_DESCRIPTION01 = 3052
}
var failureCode = Enum.GetName( reasoncode )
(当然,因为这段代码不能正常工作,因为你在名称中有重复项,但它也不会编译为常量。)