如果一个属性具有相同的名称作为它的类型? [英] Should a property have the same name as its type?
问题描述
我有时看到code这样写的:
I've sometimes seen code written like this :
public class B1
{
}
public class B2
{
private B1 b1;
public B1 B1
{
get { return b1; }
set { b1 = value; }
}
}
即。 B2级有一个名为B1属性,这也是类型B1。
i.e. class B2 has a property named "B1", which is also of type "B1".
我的直觉告诉我,这是不是一个好主意,但是否有任何技术原因,你应该避免给人一种属性相同的名称作为它的类?
My gut instinct tells me this is not a good idea, but are there any technical reasons why you should avoid giving a property the same name as its class ?
(我使用的是.NET 2.0,如果该事项)。
(I'm using .net 2.0, in case that matters).
推荐答案
它的罚款。这里典型的例子是
It's fine. The canonical example here is
public Background {
public Color Color { get; set; }
}
有罕见的问题(极端情况)而来在这里,但还不足以保证避免这种装置。坦率地说,我觉得这个设备非常有用。我不喜欢不能够做到以下几点:
There are rare issues (corner cases) that come up here, but not enough to warrant avoiding this device. Frankly, I find this device quite useful. I would not enjoy not being able to do the following:
class Ticker { ... }
public StockQuote {
public Ticker Ticker { get; set; }
}
我不希望有说新浪体育讯北京时间StockTicker
或新浪体育讯北京时间ThisTicker
等。
这篇关于如果一个属性具有相同的名称作为它的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!