Can a variable be used as a property?

I want to do something like this:

string currPanel = "Panel";
currPanel += ".Visible"

Now at this point I have a string variable with a property name that takes only boolean values. Can I do something like this:

<data type> currPanel = true;

so does the actual property Panel1.Visibleaccept it without any errors?

+4
source share
2 answers

Support for both properties and fields, but only instances:

public static void SetValue(object obj, string name, object value)
{
    string[] parts = name.Split('.');

    if (parts.Length == 0)
    {
        throw new ArgumentException("name");
    }

    PropertyInfo property = null;
    FieldInfo field = null;
    object current = obj;

    for (int i = 0; i < parts.Length; i++)
    {
        if (current == null)
        {
            throw new ArgumentNullException("obj");
        }

        string part = parts[i];

        Type type = current.GetType();

        property = type.GetProperty(part, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (property != null)
        {
            field = null;

            if (i + 1 != parts.Length)
            {
                current = property.GetValue(current);
            }

            continue;
        }

        field = type.GetField(part, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (field != null)
        {
            property = null;

            if (i + 1 != parts.Length)
            {
                current = field.GetValue(current);
            }

            continue;
        }

        throw new ArgumentException("name");
    }

    if (current == null)
    {
        throw new ArgumentNullException("obj");
    }

    if (property != null)
    {
        property.SetValue(current, value);
    } 
    else if (field != null)
    {
        field.SetValue(current, value);
    }
}

usage example:

public class Panel
{
    public bool Visible { get; set; }
}

public class MyTest
{
    public Panel Panel1 = new Panel();

    public void Do()
    {
        string currPanel = "Panel1";
        currPanel += ".Visible";

        SetValue(this, currPanel, true);
    }
}

and

var mytest = new MyTest();
mytest.Do();

, (, Panel1[5].Something). int ( 30 ). int (, ["Hello"]) (, [1, 2]) .

+2

Source: https://habr.com/ru/post/1629577/


All Articles