C# 如何用点声明属性?



我知道根据命名约定不建议这样做。

有一个C#控制台程序(.NET Framework),它是在我们的团队中编写的,它从第三方存储中获取数据并将其存储在SQL中。存储中的新列之一的名称为"ABC"。XYZ'(带".")。我们现在正在尝试为本专栏提取数据。

在代码之后,我们通常声明一个与存储列中同名的属性。 然后使用PropertyInfo,我们与从存储中获取的列名称进行匹配,并提取该特定属性名称的数据。但是在 C# 类中,我们不能在名称中声明带有 '." 的属性 -

public float ABC.XYZ {get; set;}

我尝试使用[显示名称(" ")]属性,但这不会覆盖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")].

参考这里。

[DisplayName("ABC.XYZ")]
[Column("ABC.XYZ")]
public float ABC_XYZ {get; set;}

最新更新