[Serializable]
[TableName("tUser")]
public class User
{}
……………………………………
通过反射如何得到User类的TableName属性中的"tUser"的值~??

解决方案 »

  1.   

    http://community.csdn.net/Expert/TopicView3.asp?id=5415216
      

  2.   

    using System;
    using System.Reflection;
    using System.Threading;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                GetAttributeValue(new Exa());            Console.ReadKey();
            }        static void GetAttributeValue(object obj)
            {
                Type type = obj.GetType();            PropertyInfo[] pis = type.GetProperties();  // 获取此对象所有属性.
                foreach (PropertyInfo pi in pis)
                {
                    object[] objs = pi.GetCustomAttributes(true);   // 这里获取每个属性的自定义属性(Attribute).
                    foreach (object o in objs)
                    {
                        Console.WriteLine(o.GetType().FullName);
                        Console.WriteLine(((ValueAttribute)o).Value);
                    }
                }
            }
        }    class Exa
        {
            [Value("This is a example")]
            public string Content
            {
                get { return "Content Value"; }
                set { }
            }        public string Name
            {
                get { return "Name Value"; }
                set { }
            }
        }    class ValueAttribute : Attribute
        {
            string s = "";        public ValueAttribute(string str)
            {
                s=str;
            }        public string Value
            {
                get{return s;}
            }
        }
    }
      

  3.   

    User user = new User();
                object[] objs = user.GetType().GetCustomAttributes(typeof(TableNameAttribute), false);
                foreach (object obj in objs)
                {
                    TableNameAttribute tn = (TableNameAttribute)obj;
    //tn.属性
                }
      

  4.   


            static void GetAttributeValue(object obj)
            {
                Type type = obj.GetType();            PropertyInfo[] pis = type.GetProperties();  // 获取此对象所有属性.
                foreach (PropertyInfo pi in pis)
                {
                    object[] objs = pi.GetCustomAttributes(true);   // 这里获取每个属性的自定义属性(Attribute).
                    foreach (object o in objs)
                    {
                        Console.WriteLine(o.GetType().FullName);
                        Console.WriteLine(((ValueAttribute)o).Value);
                    }
                }
            }
      

  5.   

    例如:[....]
    class TableNameAttribute:Attribute
    {
      public Name;
      public TableName(string Name){ this.Name=Name;}
    }程序中:TableNameAttribute tn=(TableNameAttribute)Attribute.GetCustomAttribute(
      typeof(User),typeof(TableNameAttribute));
    if(tn!=null)
    {
      string result=tn.Name;
      ......