gpt4 book ai didi

c# - 你如何检查一个字符串是否存在于常量中

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:32 24 4
gpt4 key购买 nike

请不要告诉我改用枚举。如何检查“testStr”是否在结构“Supplier”中?

public struct Supplier {
public const string
NA = "N/A",
companyA = "companyA",
companyB = "companyB";
}

string testStr = "companyA";

最佳答案

这可以通过反射来实现:

void Main()
{
// make sure that we only take public static const
string phrase = "companyA";
var fields = typeof(Supplier).GetFields(BindingFlags.Static | BindingFlags.Public).Where(i => i.IsLiteral);
foreach (FieldInfo field in fields)
{
string val = field.GetRawConstantValue().ToString();
string msg = string.Format("is '{0}' equal to '{1}' => {2}", val, phrase, val == phrase);
Console.WriteLine(msg);
}
}

// Define other methods and classes here
public struct Supplier {
public const string
NA = "N/A",
companyA = "companyA",
companyB = "companyB";
};

关于c# - 你如何检查一个字符串是否存在于常量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11725857/

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