Dictionary mapping strings to properties

后端 未结 2 508
粉色の甜心
粉色の甜心 2020-12-21 13:14

I have a class where I would like to return the value of various properties based on a string that I can define as an attribute like so:

    [FieldName(\"dat         


        
2条回答
  •  梦毁少年i
    2020-12-21 13:33

    You are on the right track. See below with an example similar to what you have.

    Dictionary> dic = new Dictionary>();
    private void test()
    {
        Button btn = new Button();
        btn.Text = "BlahBlah";
        dic.Add("Value", () => btn.Text);
    }
    
    private void test2()
    {
        Func outval;
        dic.TryGetValue("Value", out outval);
        MessageBox.Show(outval());
    }
    

    In the example test(), I define a new Button class and assign a value to its .Text property. Then I add a new entry into my Dictionary<>. In test2() I retrieve that Func and invoke it, which returns the string value of btn.Text.

提交回复
热议问题