c# - 如何避免对类名和属性名使用相同的标识符?

标签 c# entity-framework class properties naming-conventions

以下是共享相同标识符的类和属性的几个示例:

public Coordinates Coordinates { get; set; }
public Country Country { get; set; }
public Article Article { get; set; }
public Color Color { get; set; }
public Address Address { get; set; }
public Category Category { get; set; }

当将 POCO 与 Entity Framework 一起使用时,此问题会更频繁地发生,因为 Entity Framework 将属性名称用于关系。

那怎么办?使用非标准类名?

public ClsCoordinates Coordinates { get; set; }
public ClsCountry Country { get; set; }
public ClsArticle Article { get; set; }
public ClsColor Color { get; set; }
public ClsAddress Address { get; set; }
public ClsCategory Category { get; set; }

是的

或者使用更具描述性的属性名称?

public Coordinates GeographicCoordinates { get; set; }
public Country GeographicCountry { get; set; }
public Article WebArticle { get; set; }
public Color BackgroundColor { get; set; }
public Address HomeAddress { get; set; }
public Category ProductCategory { get; set; }

不太理想,但我想可以接受。

还是忍受它?

您有哪些最佳实践?

最佳答案

这有时被称为“颜色颜色”问题 - 我的建议是接受它。

C# 语言规范的设计使这不再成为问题。来自 C# 3 规范的第 7.5.4.1 节:

In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name (§7.5.2) is a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name (§3.8), then both possible meanings of E are permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be a member of the type E in both cases. In other words, the rule simply permits access to the static members and nested types of E where a compile-time error would otherwise have occurred.

(后面有一个例子。)

显然,当您可以提供更具描述性的属性名称时,这很好 - 但通常最好的名称​​是与属性相同的名称。

这发生在框架本身 - 例如,HttpWebRequest.CookieContainerCookieContainer 类型,并且有多种类型带有 Evidence Evidence 类型的属性。

关于c# - 如何避免对类名和属性名使用相同的标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2542963/

相关文章:

c# - 具有数据库事务的工作单元模式

c# - 将 Func 传递给 Linq to Entities Sum(..)

java - ListView 将刷新已存在的项目,并且不会添加新项目

class - 为什么 Swift 初始化器不能在它们的父类(super class)上调用便利初始化器?

python - 由属性确定的唯一数据库条目

c# - 伪造模拟数据 2 个不同属性的相同值

c# - 实例化对象速记

c# - Linq Except 未按预期运行 - 重复项目

c# - 使用 ScheduledTaskAgent 更新锁定屏幕

c# - 从图像列可能为空的数据库加载图片框图像