gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:07:17 25 4
gpt4 key购买 nike

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

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/

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