为什么C#不允许一般属性? [英] Why does C# not allow generic properties?

查看:102
本文介绍了为什么C#不允许一般属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,为什么我不能在非通用类通用的财产,我可以有泛型方法的方式。即:

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
}

我看了@乔恩飞碟双向的回答,但它只是一个说法,这极有可能是在规范中的某个地方。

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".

但更重要的是,它被认为是带来任何好处,因为它没有任何意义语义上有一个类型参数化的属性。 A 类可能有一个重量属性,但它是没有意义有一个重量和LT ;水果GT; 重量和LT;长颈鹿方式&gt; 属性

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#不允许一般属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆