首页 > 解决方案 > 如何强制一个类只接受某些数据类型

问题描述

我想知道如何将特定过滤器应用于类声明以便只接受某些数据类型。

假设我想要以下两个课程:

// 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];
            .....                
        }
    }
}

标签: c#genericsfilter

解决方案


推荐阅读