Loop through constant members of a class

2020-02-12 02:31发布

问题:

I have a class with constant strings in it. I'd like to throw all of those strings into a drop down collection. What is the best way to do this? This is what I have now and in theory, I would think that it would be the best way to do this.

public class TestClass
{
    private const string _testA = "Test A";
    private const string _testB = "Test B";

    public string TestA
    {
        get { return _testA; }
    }

    public string TestB
    {
        get { return _testB; }
    }
}

public DropDownItemCollection TestCollection
{
    DropDownItemCollection collection = new DropDownItemCollection();
    TestClass class = new TestClass();

    foreach (string testString in class)
    {
        DropDownItem item = new DropDownItem();
        item.Description = testString;
        item.Value = testString;
        collection.Add(item);
    }

    return collection;
}

The problem is that this returns an error on the foreach: "...does not contain a public definition for GetEnumerator." I've tried to create a GetEnumerator but I've been unsuccessful and I haven't worked with GetEnumerator in the past.

Any help is greatly appreciated!

回答1:

You could use reflection to loop through all the properties:

public DropDownItemCollection TestCollection
{
    var collection = new DropDownItemCollection();
    var instance = new TestClass();
    foreach (var prop in typeof(TestClass).GetProperties())
    {
        if (prop.CanRead)
        {
            var value = prop.GetValue(instance, null) as string;
            var item = new DropDownItem();
            item.Description = value;
            item.Value = value;
            collection.Add(item);
        }
    }
    return collection;
}


回答2:

A little late but wouldn't this be a better solution?

http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx

private FieldInfo[] GetConstants(System.Type type)
{
    ArrayList constants = new ArrayList();

    FieldInfo[] fieldInfos = type.GetFields(
        // Gets all public and static fields

        BindingFlags.Public | BindingFlags.Static | 
        // This tells it to get the fields from all base types as well

        BindingFlags.FlattenHierarchy);

    // Go through the list and only pick out the constants
    foreach(FieldInfo fi in fieldInfos)
        // IsLiteral determines if its value is written at 
        //   compile time and not changeable
        // IsInitOnly determine if the field can be set 
        //   in the body of the constructor
        // for C# a field which is readonly keyword would have both true 
        //   but a const field would have only IsLiteral equal to true
        if(fi.IsLiteral && !fi.IsInitOnly)
            constants.Add(fi);           

    // Return an array of FieldInfos
    return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}

If you need the names you can do

fi.GetValue(null)

inside the loop.



回答3:

You could implement a method that yields the strings:

public Ienumerable<string> GetStrings(){
   yield return TestA;
   yield return TestB;
}

Else you should look into reflection to return the properties that are static and string and then get the values by calling them.

Regards GJ



回答4:

I just had the same challenge; to get all constants of my class (not properties!). Based on the most popular answer (for properties) and John's answer (for constants) I wrote this. I tested it and it works well.

private List<string> lstOfConstants= new List<string>();
    foreach (var constant in typeof(TestClass).GetFields())
    {
        if (constant.IsLiteral && !constant.IsInitOnly)
        {
            lstOfConstants.Add((string)constant.GetValue(null));
        }
    }


回答5:

You can use reflection to loop trought the class properties:

var instance = new TestClass();
foreach(PropertyInfo pi in typeof(TestClass))
{
      var val = pi.GetValue(instance,null);
}


回答6:

You need to use reflection to get name of each String from your custom type, and then also/optionally get the value of each one of those Strings...

Something like this:

TestClass theClass = new TestClass();

foreach (PropertyInfo property in theClass.GetType().GetProperties())
{

    Console.WriteLine(property.Name);
    Console.WriteLine(property.GetValue(theClass, null));
}


标签: c# class