如何解决C#如何用点声明属性?
我知道根据命名约定不推荐这样做。
有一个 C# 控制台程序(.NET Framework),它是我们团队很久以前编写的,它从第三方存储中获取数据并将其存储在 SQL 中。存储中的新列之一的名称为“ABC.XYZ”(带有“.”)。我们现在正在尝试为该列提取数据。
按照代码,我们通常会声明一个与存储列中名称相同的属性。然后使用 PropertyInfo 与从存储中获取的列名称进行匹配,并提取该特定属性名称的数据。但是在 C# 类中,我们不能用 '.' 声明一个属性。名义上 -
public float ABC.XYZ {get; set;}
我尝试使用 [DisplayName(" ")] 属性,但这不会覆盖 PropertyInfo.Name 值 -
[DisplayName("ABC.XYZ")]
public float ABC.XYZ {get; set;}
我怎样才能以更好的方式实现这一点?
解决方法
您不能有一个带有 .
的 C# 属性名称,所以;那不是一个选择。并且添加 [DisplayName]
不会更改属性名称 - 此添加仅对显式检查属性数据的代码可见。不过,听起来您有自己的代码来检查以进行查找。您可以教育那个代码检查是否有[DisplayName]
(或类似的),例如:
PropertyInfo prop = // ... your code here;
var dn = (DisplayNameAttribute)prop.GetCustomAttribute(typeof(DisplayNameAttribute));
var name = dn?.DisplayName; // use the display name if there is one
if (string.IsNullOrWhiteSpace(name))
{
name = prop.Name; // but use the regular property name if there isn't
}
请注意,反射元数据查找效率不高;您通常希望尽可能少地执行此操作,缓存结果。
旁注:我个人建议为此定义您自己的属性,而不是滥用 DisplayNameAttribute
。这并不复杂:
[AttributeUsage(AttributeTargets.Property,AllowMultiple = false)]
sealed class WhateverAttribute : Attribute
{
public string ColumnName { get; }
public WhateverAttribute(string columnName)
=> ColumnName = columnName;
}
并使用 [Whatever("ABC.DEF")]
并记住将上面代码中的 DisplayNameAttribute
更改为 WhateverAttribute
。
最后,不要忘记更新任何 SQL 代以检查 .
并使用适当的转义 - 例如,在 SQL Server 中,此列需要引用为 [ABC.DEF]
以避免混淆你说的.
是什么意思。
也许可以试试注释 [Column("ABC.XYZ")]
。
参考here。
[DisplayName("ABC.XYZ")]
[Column("ABC.XYZ")]
public float ABC_XYZ {get; set;}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。