mardi 10 juillet 2018

Accessing element in Array, Dictionary or List using Reflection

Ive created a tool for my team which allows them to view an object visually by using the Dump() method of LinqPad. This is purely for use by the development teams to make things easier rather than having to attach a debugger which isnt always possible.

They enter the name of the object they want to Dump and the program does it in its current context.

eg. User enters Sales.CurrentUser and the application visualises the CurrentUser object using LinqPad's Dump() method.

public void VisualiseObject()
{
    object CurrentObject = this;

    string Result = GetObjectFromUser("Enter Propery or Field path eg. Sales.CurrentUser", "");

    if (Result == null)
        return;
    else if (Result != string.Empty)
    {    
        string[] Objects = Result.Split(".".ToCharArray());

        try
        {
            foreach (string objName in Objects)
            {
                CurrentObject = GetPropValue(CurrentObject, objName);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        if (CurrentObject == null)
        {
            MessageBox.Show("Object is null");
            return;
        }
    }

    CurrentObject.Dump(Result);
}

public static object GetPropValue(object src, string propName)
{
    object result = null;

    try
    {
        result = src.GetType().GetProperty(propName).GetValue(src, null);
    }
    catch
    {
        try
        {
            result = src.GetType().GetField(propName).GetValue(src);
        }
        catch (Exception)
        {
            result = null;
        }
    }

    return result;
}   

Anyway im trying to think of a way to support the user supplying an index or key to a array, list or dictionary object and handle this in reflection.

The user could supply for example. An array or list Sales.AllUsers[0] or for dictionary Sales.Items["Water"]

Any ideas?





Aucun commentaire:

Enregistrer un commentaire