如果是值类型/引用类型约束在C#有用吗? [英] When is a value type / reference type constraint useful in C#?

查看:80
本文介绍了如果是值类型/引用类型约束在C#有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找当值类型/引用类型约束是有用的演示简单的例子。

I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

... where T : struct  // when is this useful?
... where T : class   // and what about this?



我记得看到一些非常好的例子,在过去,但我无法找到他们。

I remember seeing some very nice examples in the past but I just can't find them.

推荐答案

它允许您使用运营商对T,如果它是 T:类

It allows you to use as operator on T if it is T:class.

它禁止你与空如果T T:结构

请注意,如果你省略 T:类,那么你可以比较T可空,即使T是值类型

Note that if you omit T:class then you can compare T to null even when T is a value type.

[注:我需要前几次编辑这个职位它得到正确的。至少我希望它现在是正确的。]

[Note: I needed to edit this post a few times before it got correct. At least I hope it is now correct.]

这篇关于如果是值类型/引用类型约束在C#有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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