从父类调用属性,如c#中的字典

时间:2017-03-30 12:00:44

标签: c#

我可能不知道怎么看,但事实是我找不到任何可以帮助我的东西。

有没有办法从父类调用属性,如关联数组(字典)?

样品:

using System;

class Foobar
{
    public string bla;
    public Foobar()
    {
        this.bla = "hello world";
    }
}

public class Test
{
    public static void Main()
    {
        Foobar x = new Foobar();
        Console.WriteLine(x.bla); //this works (prints hello world)
        Console.WriteLine(x["bla"]); //this wont work but is my achivment
    }
}

澄清我想要的是......

我想创建一个具有某些属性的类,例如

class SomeClass
{
    private string aaa {get;set;};
    private string bbb {get;set;};
    private string ccc {get;set;};
    private string ddd {get;set;};
    ....
}

而不是通过字典在其他类中循环

SomeClass x = new SomeClass();
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["a"] = "aaa";
dict["b"] = "bbb";
dict["d"] = "ddd";

foreach( d in dict )
{
    someMethode(x[d]);
}

2 个答案:

答案 0 :(得分:4)

以这种方式修改你的课程

class Foobar
{
    public string bla { get; set; }
    public Foobar()
    {
        this.bla = "hello world";
    }

    public string this[string name]
    {
        get
        {
            return this.GetType().GetProperty(name).GetValue(this, null).ToString();
        }
    }
}

示例:https://dotnetfiddle.net/XboHOg

答案 1 :(得分:1)

你应该以这种方式扩展它^^

using System;


    class Program
    {
        static void Main(string[] args)
        {
            Foobar x = new Foobar();
            Console.WriteLine(x.bla); //this works (prints hello world)
            Console.WriteLine(x["bla"]); //this wont work but is my achivment
        }
    }

    class Foobar : Class
    {
        public Foobar()
        {
            this.bla = "hello world";
        }

        public string bla { get; set; }
    }

    class Class
    {
        public string this[string name]
        {
            get
            {
                return this.GetType().GetProperty(name).GetValue(this).ToString();
            }
        }
    }