c# - 如何强制一个类只接受某些数据类型
问题描述
我想知道如何将特定过滤器应用于类声明以便只接受某些数据类型。
假设我想要以下两个课程:
// Here, T can only be an array type. ie. int[], uint[], byte[], etc.
public class myClassArray<T> where T is Array
{
}
// Here, T can only be an integral numeric type. ie. int, uint, byte, etc.
public class myClassNotArray<T> where T is NotAnArray
{
}
在这两种情况下,我仍然希望能够进行基本的算术运算。
我尝试了很多东西,但一切都失败了。我认为这是因为我并不真正了解特定数据类型的特征以及如何找出其特征。
例如和 Array 似乎实现:
"ICloneable, System.Collections.IList, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable"
但不知何故,做这样的事情仍然不允许我做算术:
public class myClassArray<T> where T : ICloneable, System.Collections.IList, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable
{
public voidDoSomeStuff(T value1, T value2)
{
// I would like this to work:
for (int idx = 0; idx < value1.Count(); idx++)
{
var result = value1[idx] - value2[idx];
.....
}
}
}
解决方案
推荐阅读
- pandas - 尝试遍历一列以填充另一列
- css - 样式组件在外部 scss 文件中不起作用
- python - discord.py 更改前缀命令缩进错误
- c# - 如何从 c# net core 中的静态路径(cdn)获取物理路径
- python - 有没有办法在 matplotlib 图形轴中显示文本?
- c++ - How to detect C++ valid identifiers using regex?
- c# - Can XAML "deduce" inheritance from C#?
- react-native - react-native switch between two navigation components
- python - Django is having trouble finding static folder/css
- javascript - 如何存储数组
在 Javascript 的本地存储中?