is it possible to enumerate the public static strings in an object?
In this code they've u开发者_JAVA百科sed this construction instead of an enum:
a public class with all public static strings.
Is it possible to enumerate over static strings in a class?
This will enumerate string values of public static fields in the class MyClass
:
var flags = BindingFlags.Public | BindingFlags.Static;
var query = typeof(MyClass)
.GetFields(flags)
.Where(fieldInfo => fieldInfo.FieldType == typeof(string))
.Select(fieldInfo => fieldInfo.GetValue(null));
foreach (var value in query) {
// ...
}
For public static properties it is almost the same:
var flags = BindingFlags.Public | BindingFlags.Static;
var query = typeof(MyClass)
.GetProperties(flags)
.Where(propertyInfo => propertyInfo.PropertyType == typeof(string))
.Select(propertyInfo => propertyInfo.GetValue(null, null));
foreach (var value in query) {
// ...
}
Use reflection:
yourobject.GetType().GetFields(BindingFlags.Static|BindingFlags.Public)
will return all the static field of your class.
I started writing this before the other answers so might as well post my answer too.
public class PublicStringIteration
{
static void Main(string[] args)
{
MyStrings myStrings = new MyStrings();
foreach (string value in myStrings.GetStaticFieldValues())
{
Console.WriteLine(value);
}
}
}
public class MyStrings
{
public static string String1 = "String1 Value";
public static string String2 = "String2 Value";
public static string String3 = "String3 Value";
}
public static class MyStringsExtensions
{
public static IEnumerable<string> GetStaticFieldValues(this MyStrings myStrings)
{
Type myClassType = typeof(MyStrings);
foreach (MemberInfo info in myClassType.GetMembers())
{
if (info.MemberType == MemberTypes.Field)
{
yield return myClassType.GetField(info.Name).GetValue(info).ToString();
}
}
}
}
精彩评论