当前位置:编程学习 > C#/ASP.NET >>

C#如何通过一个字符串找到一个动态类的属性值

如题,如一个动态类如下:
public class a
{
  public a1{get;set;}
}

想通过"a1",对应a类的a1属性。怎么办到! --------------------编程问答-------------------- 反射,xxx.GetType().GetProperty --------------------编程问答-------------------- 这个要用到反射,你搜索一下反射的例子吧 --------------------编程问答--------------------
class Program
    {
        static void Main(string[] args)
        {
            a a1111 = new a();
            a1111.a1 = "hello.";

            Type type = a1111.GetType();
            string name = "a1";//输出属性的名称
            PropertyInfo pi = type.GetProperties().FirstOrDefault(x => x.Name == name);
            Console.WriteLine(pi.GetValue(a1111, null));//输出:hello.
        }
    }

    public class a
    {
        public string a1 { get; set; }
    }
--------------------编程问答-------------------- 今天刚好用到动态赋值 class golog = new class ();
                Type type = typeof(class);
              PropertyInfo[] pi = type.GetProperties();
             foreach (PropertyInfo item in pi)
                    {
                        if (item.Name.Equals(参数名称))
                        {
                            item.GetValue();
                            break;
                        }
                    }
GetValue具体没用过 参数你自己可以看看 --------------------编程问答-------------------- 写了半天居然这么多大神回答了  --------------------编程问答-------------------- 反射得到对象属性数组- -
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,