我创建了自定义属性并放在Core.dll中。
public class DBColumnReference : Attribute
{
string m_column;
public string ColumnName {
get { return m_column; }
}
public DBColumnReference(string column)
{
m_column = column;
}
}
然后我创建了我的应用程序,它引用了Core.dll 在我的应用程序中创建自己的对象,并在一些属性上使用我的Core.dll自定义属性。
public class TestingObject4
{
string m_table = "TESTING_CORE_OBJECT4";
public string Table
{
get { return m_table; }
}
private int m_id = 0;
[DBColumnReference("ID")]
public int Id
{
get { return m_id; }
set { m_id = value; }
}
我调用Core方法" FilterProperties(typeof(TestingObject4))"哪个按属性过滤属性。
private static Dictionary<string, PropertyInfo> FilterProperties(Type type)
{
Dictionary<string, PropertyInfo> result = new Dictionary<string, PropertyInfo>();
if(type == null)
return result;
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo prop in properties)
{
// Attribute[] atributes = Attribute.GetCustomAttributes(prop, true);
object[] atributes = prop.GetCustomAttributes(typeof(DBColumnReference), true);
if(atributes != null && atributes.Length != 0)
{
DBColumnReference reference = atributes[0] as DBColumnReference;
result.Add(reference.ColumnName, prop);
}
}
return result;
}
Attributes[]
属性始终为空。如何正确获取属性?
答案 0 :(得分:1)
试试这个片段对我有用!
public class DBColumnReference : Attribute
{
string m_column;
public string ColumnName
{
get { return m_column; }
}
public DBColumnReference(string column)
{
m_column = column;
}
}
public class TestingObject4
{
string m_table = "TESTING_CORE_OBJECT4";
public string Table
{
get { return m_table; }
}
private int m_id = 0;
[DBColumnReference("an integer id")]
public int Id
{
get { return m_id; }
set { m_id = value; }
}
}
class Program
{
private static Dictionary<string, PropertyInfo> FilterProperties(Type type)
{
Dictionary<string, PropertyInfo> result = new Dictionary<string, PropertyInfo>();
if (type == null)
return result;
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo prop in properties)
{
// Attribute[] atributes = Attribute.GetCustomAttributes(prop, true);
object[] atributes = prop.GetCustomAttributes(typeof(DBColumnReference), true);
if (atributes != null && atributes.Length != 0)
{
DBColumnReference reference = atributes[0] as DBColumnReference;
result.Add(reference.ColumnName, prop);
}
}
return result;
}
static void Main(string[] args)
{
Dictionary<string, PropertyInfo> resultCollection = FilterProperties(typeof(TestingObject4));
foreach (var singleObject in resultCollection)
{
Console.WriteLine(singleObject.Key + " " + singleObject.Value);
}
Console.ReadKey(false);
}
}