제네릭에 대해 배우기 때문에 문자열 배열 또는 숫자 데이터 배열을 만드는 데 사용할 수있는 제네릭 배열 클래스를 만들려고합니다. 이 제네릭 클래스에는 몇 가지 다른 메서드가 있습니다. 예를 들어 데이터를 추가하고 데이터를 제거하고 데이터를 검색 할 수 있습니다. 이러한 모든 메서드는 숫자 데이터를 사용하는 매력처럼 작동하지만 참조 형식이고 기본값이 null이므로 내 메서드에서 null 예외를 throw하기 때문에 문자열을 사용하는 데 문제가 있습니다.제네릭 문자열에서 데이터 제거 Array C#
내 클래스는 다음과 같습니다
class MyArray<T> : IComparable<T>, IEnumerable<T>, IEnumerator<T>
{
T[] data = new T[10];
private int currentIndex = 0;
//This method works as intended, both with strings and ints
public void Add(T Value)
{
data[currentIndex] = Value;
currentIndex++;
if (currentIndex == data.Length)
{
T[] tmp = new T[data.Length + 10];
data.CopyTo(tmp, 0);
data = tmp;
}
}
//Can't figure out how to make this method work with strings
public void RemoveItem(T Value)
{
T[] tmp = new T[data.Length - 1];
int i = 0;
foreach (T ele in data)
{
if (!ele.Equals(Value))//This line gives me a nullRefException when I'm using strings
{
tmp[i] = ele;
i++;
}
}
data = tmp;
}
나는 데이터를 추가하고 다음과 같습니다 제거하기 위해 노력하고있어 내 기본 양식 : 나는 알아낼 수 없습니다
static void Main(string[] args)
{
MyArray<string> StringArray = new MyArray<string>();
StringArray.Add("1");
StringArray.Add("2");
StringArray.RemoveItem("2");
}
null의 기본값 때문에 문자열 인 경우 데이터를 다시 제거하는 영리한 방법입니다. 사전 :
가 궁금 수 있습니다 당신은'목록'대신를 사용하지 않는 이유는 무엇입니까? 이 모든 것을 상자에서 꺼낼 때? –
balexandre