C# 如何定义基本类型的泛型类型限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/805264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:53:47  来源:igfitidea点击:

How to define generic type limit to primitive types?

c#.netgenericstype-constraints

提问by David.Chu.ca

I have the following method with generic type:

我有以下通用类型的方法:

T GetValue<T>();

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:

我想将 T 限制为原始类型,例如 int、string、float 而不是类类型。我知道我可以像这样为类类型定义泛型:

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

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

我不确定原始类型是否可行,以及如何实现。

回答by BFree

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.

你还提到了字符串。不幸的是,不允许使用字符串,因为它们不是值类型。

回答by Joshua Belden

Here's what you're looking for:

这就是你要找的:

T GetObject<T>() where T : struct;

回答by David McEwing

What are you actually trying to do in the method? It could be that you actually need C to implement IComparable, or someother interface. In which case you want something like

你实际上想在这个方法中做什么?可能是您实际上需要 C 来实现 IComparable 或其他接口。在这种情况下,您想要类似的东西

T GetObject<T> where T: IComparable

回答by Marc Gravell

There is no generic constraint that matches that set of things cleanly. What is it that you actually want to do? For example, you can hack around it with runtime checks, such as a static ctor (for generic types - not so easy for generic methods)...

没有与这组事物完全匹配的通用约束。你真正想做的是什么?例如,您可以使用运行时检查来绕过它,例如静态构造函数(对于泛型类型 - 对于泛型方法来说不是那么容易)...

However; most times I see this, it is because people want one of:

然而; 大多数时候我看到这一点,这是因为人们想要以下之一:

  • to be able to check items for equality: in which case use EqualityComparer<T>.Default
  • to be able to compare/sort items: in which case use Comparer<T>.Default
  • to be able to perform arithmetic: in which case use MiscUtil's support for generic operators
  • 能够检查项目是否相等:在这种情况下使用 EqualityComparer<T>.Default
  • 能够比较/排序项目:在这种情况下使用 Comparer<T>.Default
  • 能够执行算术运算:在这种情况下,请使用MiscUtil泛型运算符的支持

回答by Deko

Actually this does the job to certain extend:

实际上,这在一定程度上起到了作用:

public T Object<T>() where T :
   struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>

To limit to numeric types you can get some useful hints of the following samples defined for the ValueTypeclass

要限制为数字类型,您可以获得以下为ValueType类定义的示例的一些有用提示