[Serializable]
[TableName("tUser")]
public class User
{}
……………………………………
通过反射如何得到User类的TableName属性中的"tUser"的值~??
[TableName("tUser")]
public class User
{}
……………………………………
通过反射如何得到User类的TableName属性中的"tUser"的值~??
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;}
}
}
}
object[] objs = user.GetType().GetCustomAttributes(typeof(TableNameAttribute), false);
foreach (object obj in objs)
{
TableNameAttribute tn = (TableNameAttribute)obj;
//tn.属性
}
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 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;
......