问题描述
我想知道为什么我不能像拥有泛型方法那样在非泛型类中拥有泛型属性.即:
I was wondering why I can not have generic property in non-generic class the way I can have generic methods. I.e.:
public interface TestClass
{
IEnumerable<T> GetAllBy<T>(); //this works
IEnumerable<T> All<T> { get; } //this does not work
}
我阅读了@Jon Skeet 的答案,但这只是一个声明,很可能在规范中的某处.
I read @Jon Skeet's answer, but it's just a statement, which most probably is somewhere in the specifications.
我的问题是为什么实际上是这样?这种限制是否避免了一些问题?
My question is why actually it is that way? Was kind of problems were avoided with this limitation?
推荐答案
从技术上讲,CLR 只支持泛型类型和方法,不支持属性,所以问题是为什么没有将它添加到 CLR 中.对此的答案可能很简单:人们认为它带来的收益不足以值得付出代价".
Technically, the CLR supports only generic types and methods, not properties, so the question is why it wasn’t added to the CLR. The answer to that is probably simply "it wasn’t deemed to bring enough benefit to be worth the costs".
但更根本的是,它被认为没有任何好处,因为通过类型参数化属性在语义上没有意义.Car
类可能有一个 Weight
属性,但是拥有一个 Weight
和一个 Weight 是没有意义的;
属性.
But more fundamentally, it was deemed to bring no benefit because it doesn’t make sense semantically to have a property parameterised by a type. A Car
class might have a Weight
property, but it makes no sense to have a Weight<Fruit>
and a Weight<Giraffe>
property.
这篇关于为什么 C# 不允许泛型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!