【发布时间】:2010-12-21 04:54:46
【问题描述】:
我想实现一个集合,它的项目需要进行空性测试。 在引用类型的情况下,将测试是否为空。对于值类型,必须实现空测试,并且可能选择一个表示空的特定值。
我的 T 通用集合应该可用于值和引用类型值(这意味着 Coll<MyCalss> 和 Coll<int> 都应该是可能的)。但我必须以不同的方式测试引用和值类型。
拥有一个实现 IsEmpty() 方法的接口以从我的泛型类型中排除此逻辑不是很好吗?但是当然,这个 IsEmpty() 方法不能是成员函数:它不能在空对象上调用。
我发现的一种解决方法是将集合项存储为对象,而不是 T-s,但这让我很头疼(围绕装箱和强类型)。在好的旧 C++ 中没问题 :-)
下面的代码演示了我想要实现的目标:
using System;
using System.Collections.Generic;
namespace StaticMethodInInterfaceDemo
{
public interface IEmpty<T>
{
static T GetEmpty(); // or static T Empty;
static bool IsEmpty(T ItemToTest);
}
public class Coll<T> where T : IEmpty<T>
{
protected T[] Items;
protected int Count;
public Coll(int Capacity)
{
this.Items = new T[Capacity];
this.Count = 0;
}
public void Remove(T ItemToRemove)
{
int Index = Find(ItemToRemove);
// Problem spot 1: This throws a compiler error: "Cannot convert null to type parameter 'T'
// because it could be a non-nullable value type. Consider using 'default(T)' instead."
this.Items[Index] = null;
// To overcome, I'd like to write this:
this.Items[Index] = T.Empty; // or T.GetEmpty(), whatever.
this.Count--;
}
public T[] ToArray()
{
T[] ret = new T[this.Count];
int TargetIndex = 0;
for(int Index = 0; Index < this.Items.GetLength(0); Index++)
{
T Item = this.Items[Index];
// Problem spot 2: This test is not correct for value types.
if (Item != null)
ret[TargetIndex++] = Item;
// I'd like to do this:
if (!T.IsEmpty(Item))
ret[TargetIndex++] = Item;
}
return ret;
}
protected int Find(T ItemToFind)
{
return 1; // Not implemented in the sample.
}
}
}
【问题讨论】:
-
您希望静态接口方法如何准确工作?运行 IFoo.SomeStaticMethod 时会调用什么?
-
这个问题也可能提供一些相关信息stackoverflow.com/questions/259026/…
标签: c# interface static methods