gpt4 book ai didi

c# - 来自其他 dll 的 PropertyInfo GetCustomAtributes

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:25 24 4
gpt4 key购买 nike

我创建了我的自定义属性并放置在 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; }
}

我调用核心方法“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[] 属性总是空的。如何正确获取属性?

最佳答案

试试这个对我有用的片段!

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);
}
}

关于c# - 来自其他 dll 的 PropertyInfo GetCustomAtributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10371460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com