c#属性数据注释



是否有办法读取,哪些注释被绑定到属性?

我有这样的代码。

[PrimaryKey]
[Identity]
public int Id { get; set; }
[ForeignKey]
public int OwnerId { get; set; }
[ForeignKey]
public int RegionId { get; set; }
public string Name { get; set; } = null!;
public double Price { get; set; }

,我想知道属性是否有Id和Annotation,如果是什么类型。一个属性可以有多个注释吗?

我的阅读代码是这样的,没有包含注释

var type = typeof(TValue);
var properties = type.GetProperties();
var name = type.Name;
string[] propertySQLstring = new string[properties.Length];
string[] valueSQLstring = new string[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
if (i + 1 == properties.Length)
{
propertySQLstring[i] = properties[i].Name;
valueSQLstring[i] = properties[i].GetValue(value)?.GetType() != typeof(string) ? properties[i].GetValue(value)?.ToString() : $"'{properties[i].GetValue(value)}'";
}
else
{
propertySQLstring[i] = properties[i].Name + ",";
valueSQLstring[i] = properties[i].GetValue(value)?.GetType() != typeof(string) ? properties[i].GetValue(value)?.ToString() + ',' : $"'{properties[i].GetValue(value)}', ";
}
}

提前感谢。

假设您有一个想要支持的预定义属性列表,您可以使用GetCustomAttributes()和属性的泛型类型。

foreach (PropertyInfo property in typeof(T).GetProperties())
{
IEnumerable<PrimaryKeyAttribute> primaryKeyAttributes = property.GetCustomAttributes<PrimaryKeyAttribute>();
}

如果你只想获得所有的属性,你会希望使用GetCustomAttributes()而不提供泛型类型。