可空对象通用对象集合
public class CubicMatrix<Object?>
{
private int width;
private int height;
private int depth;
private Object[, ,] matrix;
public CubicMatrix(int inWidth, int inHeight, int inDepth)
{
width = inWidth;
height = inHeight;
depth = inDepth;
matrix = new Object[inWidth, inHeight, inDepth];
}
public void Add(Object toAdd, int x, int y, int z)
{
matrix[x, y, z] = toAdd;
}
public void Remove(int x, int y, int z)
{
matrix[x, y, z] = null;
}
public void Remove(Object toRemove)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
for (int z = 0; z < depth; z++)
{
Object value = matrix[x, y, z];
bool match = value.Equals(toRemove);
if (match == false)
{
continue;
}
matrix[x, y, z] = null;
}
}
}
}
public IEnumerable<Object> Values
{
get
{
LinkedList<Object> allValues = new LinkedList<Object>();
foreach (Object entry in matrix)
{
allValues.AddLast(entry);
}
return allValues.AsEnumerable<Object>();
}
}
public Object this[int x, int y, int z]
{
get
{
return matrix[x, y, z];
}
}
public IEnumerable<Object> RangeInclusive(int x1, int x2, int y1, int y2, int z1, int z2)
{
LinkedList<Object> list = new LinkedList<object>();
for (int a = x1; a <= x2; a++)
{
for (int b = y1; b <= y2; b++)
{
for (int c = z1; c <= z2; c++)
{
Object toAdd = matrix[a, b, c];
list.AddLast(toAdd);
}
}
}
return list.AsEnumerable<Object>();
}
public bool Available(int x, int y, int z)
{
Object toCheck = matrix[x, y, z];
if (toCheck != null)
{
return false;
}
return true;
}
}
我已经在C#中创建了一个Cubic Matrix类来存储三维中的项目。我需要能够添加和删除项目,这就是为什么我使用对象? (我已经明白你不能使用可空泛型,即T?)。但是这种方法gnerates错误可空对象通用对象集合
类型参数声明必须是一个标识符不是一个类型
如果我不使用对象?虽然只是使用Object或T我得到这个错误,而不是
无法将null转换为类型参数'T',因为它可能是一个不可为空的值类型。考虑使用'default(T)'。
在这种情况下使用的正确语法和方法是什么?
我想你想使用通用参数T
。你正在创建一个简单的容器类,因此允许任何泛型参数都是有意义的,不管它是否可为空。要解决这个错误,只需按照说明操作,并使用default(T)
而不是null
。
错误是因为T
可能是class
或struct
,并且struct
s不能为空。因此,将类型为T
的变量分配给null
是无效的。 default(T)
是null
当T
是一个类,默认值为T
是一个结构。
当返回default(T)
代替(如你所得到的错误提示),引用类型将返回null
,数字类型将返回0
,您的自定义类将返回null
和nullables将返回System.Nullable<T>
。在MSDN上的default Keyword in Generic Code (C# Programming Guide) 的更多信息。
如果你想限制你的泛型类型只对象 - 即,无结构或简单的类型 - 你可以添加where
条款
public class CubicMatrix<T> where T : class
这意味着T
只能是一类。
这是不正确,结构满足['新()'](https://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx)约束。 [编译示例](http://ideone.com/hf56HY)。你可能在寻找'class'约束。 – 31eee384
@ 31eee384你是对的 - 谢谢,我已经更新了答案。 –
使用对象约束会生成错误_Constraint不能是特殊类'object'_ 但是使用where T:类约束起作用。感谢您的帮助 – Darkreaper
这里有一些可能的解决方案: http://stackoverflow.com/questions/19831157/c-sharp-generic-type-constraint-for-everything-nullable –