public class Constants
{
public const string test1 = "This is testvalue1;"
public const string test2 = "This is testvalue1;"
public const string test3 = "This is testvalue1;"
public const string test4 = "This is testvalue1;"
public const string test5 = "This is testvalue1;"
}
是否可以通过使用var propertyString = Constants.Where(<Propertyname> == test1).ToString()
来获取常量字符串?
答案 0 :(得分:4)
你必须通过反思来做到这一点。
string fieldName = "test1";
object fieldValue = typeof(Constants).GetField(fieldName, BindingFlags.Static).GetValue(null);
答案 1 :(得分:2)
除了其他面向反射的答案,您可以使用字典:
public string GetConstantValue(string key)
{
return _constants[key];
}
private Dictionary<string, string> Constants = new Dictionary<string, string>()
{
{ "test1", "This is testvalue1;" },
{ "test2", "This is testvalue2;" },
{ "test3", "This is testvalue3;" },
{ "test4", "This is testvalue4;" },
{ "test5", "This is testvalue5;" },
};
然后使用MyClass.GetConstantValue("test1")
获取常量值。
答案 2 :(得分:2)
这也可行:
foreach (var prop in typeof(Constants).GetFields())
{
string test = prop.GetRawConstantValue().ToString();
if (test == "test1")
MessageBox.Show("You got me!");
}
答案 3 :(得分:1)
您可以使用Reflection。
List<string> messages = new List<string>();
foreach (FieldInfo field in typeof(Constants).GetFields().Where(f => f.Name.StartsWith("test")))
{
messages.Add(field.GetRawConstantValue().ToString());
}
答案 4 :(得分:1)
为了得到这个,
var p = Constants.Get("test1");//gives 'This is testvalue1'
你可以这样做 -
public class Constants
{
public const string test1 = "This is testvalue1";
public const string test2 = "This is testvalue1";
public const string test3 = "This is testvalue1";
public const string test4 = "This is testvalue1";
public const string test5 = "This is testvalue1";
public static string Get(string propertyName)
{
var value = (string)(typeof(Constants).GetField(propertyName,BindingFlags.Static | BindingFlags.Public).GetValue(null));
return value;
}
}
答案 5 :(得分:0)
当然有可能。下面的代码使用反射来遍历类的所有常量。
internal class Program
{
public const string ConstExample = "constant value";
private static void Main(string[] args)
{
FieldInfo[] fieldInfos = typeof(Program).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
var constants = fieldInfos.Where(z => z.IsLiteral && !z.IsInitOnly).ToList();
foreach (var constant in constants)
{
string constantName = constant.Name;
object constantValue = constant.GetValue(null);
Console.WriteLine(string.Format("Constante name: {0}, constant value: {1}", constantName, constantValue));
}
Console.ReadKey();
}
}
答案 6 :(得分:0)
为了获得良好的性能和可读性,我建议使用数组和枚举。
class App
{
private enum ConstantsEnum: int
{
DefaultName = 0,
DefaultMode = 1,
DefaultStatus = 2
}
private readonly string[] Constants = new string[]{
"MyProgram",
"Test",
"Enabled" };
private void DoWork()
{
Console.WriteLine(Constants[ConstantsEnum.DefaultName]);
}
}
请注意,所有变量都必须是string
类型。如果您想混合和匹配数据类型,那么您可以使用object[]
而不是string[]
,但这样会更昂贵而且不是类型安全的。
如果您只是想找到一种方法来对某些属性进行分组,那么这比反射要好得多。