How can I get the value of a string property via Reflection?

前端 未结 9 1609
日久生厌
日久生厌 2020-11-30 04:46
public class Foo
{
   public string Bar {get; set;}
}

How do I get the value of Bar, a string property, via reflection? The following code will thr

9条回答
  •  误落风尘
    2020-11-30 05:36

    Foo f = new Foo();
    f.Bar = "Jon Skeet is god.";
    
    foreach(var property in f.GetType().GetProperties())
    {
        if(property.Name != "Bar")
        {
             continue;
        }
        object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
    }
    

    And here is for the followup:

    class Test
    {
        public class Foo
        {
            Dictionary data =new Dictionary();
            public int this[string index]
            {
                get { return data[index]; }
                set { data[index] = value; }
            }
    
            public Foo()
            {
                data["a"] = 1;
                data["b"] = 2;
            }
        }
    
        public Test()
        {
            var foo = new Foo();
            var property = foo.GetType().GetProperty("Item");
            var value = (int)property.GetValue(foo, new object[] { "a" });
            int i = 0;
        }
    }
    

提交回复
热议问题