SentineL
SentineL

Reputation: 4732

Compare class's field with it's name

I whould like to have a Dictionary, where value is field of type myClass, and key is this field's name. I tried FieldInfo:

actions = new Dictionary<string, myClass> ();
FieldInfo[] fields = triggerScript.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
int iterator = 0;

for (int i = 0; i < fields.Length; i++) 
{
    var field = fields[i];
    if (field.FieldType == typeof(myClass))
    {
        actions.Add (fields[i].Name, fields[i].GetValueDirect());
    }
}

But FieldInfo doesn't contains reference to the field it discribes. How can I do this?


Example:

public SimpleAction OnClick;

In Dictionary:

key - OnClick;

value - (SimpleAction)OnClick;

UPDATE

I have an assigned object of tyte SimpleAction, and whant to store it's reference and name in dictionary.

Upvotes: 0

Views: 324

Answers (1)

cuongle
cuongle

Reputation: 75316

You can use ToDictionary method from LINQ for simpler. Also, to get the value of Field, use method GetValue:

var actions = triggerScript.GetType()
           .GetFields(BindingFlags.Public | BindingFlags.Instance)
           .Where(field => field.FieldType == typeof (SimpleAction))
           .ToDictionary(field => field.Name, 
                         field => (SimpleAction)field.GetValue(triggerScript));

Upvotes: 1

Related Questions