如何定义泛型类型的限制基本类型? [英] How to define generic type limit to primitive types?

查看:329
本文介绍了如何定义泛型类型的限制基本类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类型下面的方法:

I have the following method with generic type:

T GetValue<T>();

我想限制T可基本类型,如int,字符串,浮点而不是类的类型。我知道我可以定义泛型类的类型是这样的:

I would like to limit T to primitive types such as int, string, float but not class type. I know I can define generic for class type like this:

C GetObject<C>() where C: class;

我不知道是否有可能为基本类型,以及如何如果是这样。

I am not sure if it is possible for primitive types and how if so.

推荐答案

您可以用它来限制它的值类型:

You can use this to limit it to value types:

where C: struct

您还别说字符串。不幸的是,字符串将不被允许,因为它们不值类型。

You also mention string. Unfortunately, strings won't be allowed as they are not value types.

这篇关于如何定义泛型类型的限制基本类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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