문제

int의 배열을 확장하고 나만의 클래스를 만들고 싶습니다. 그게 가능합니까? 내가 필요한 것은 "+"연산자가 다른 배열에 추가 할 수있는 int 배열 (각각 각 요소에 추가)을 추가하고 "=="로 비교할 수 있으므로 사전의 키로 사용할 수 있습니다.

문제는 새 클래스에 전체 ILIST 인터페이스를 구현하고 싶지 않지만 두 연산자를 기존 배열 클래스에 추가합니다.

나는 다음과 같은 일을하려고 노력하고 있습니다.

class MyArray : Array<int>

그러나 그것은 분명히 그런 식으로 작동하지 않습니다;).

불분명하다면 죄송하지만 지금 몇 시간 동안 솔루션을 찾고 있습니다 ...

업데이트:

나는 다음과 같은 것을 시도했다 :

class Zmienne : IEquatable<Zmienne>
{
    public int[] x;
    public Zmienne(int ilosc)
    {
        x = new int[ilosc];
    }
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        return base.Equals((Zmienne)obj);
    }
    public bool Equals(Zmienne drugie)
    {
        if (x.Length != drugie.x.Length)
            return false;
        else
        {
            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] != drugie.x[i])
                    return false;
            }
        }
        return true;
    }

    public override int GetHashCode()
    {
        int hash = x[0].GetHashCode();
        for (int i = 1; i < x.Length; i++)
            hash = hash ^ x[i].GetHashCode();
        return hash;
    }

}

그런 다음 다음과 같이 사용하십시오.

Zmienne tab1 = new Zmienne(2);
Zmienne tab2 = new Zmienne(2);
tab1.x[0] = 1;
tab1.x[1] = 1;

tab2.x[0] = 1;
tab2.x[1] = 1;

if (tab1 == tab2)
    Console.WriteLine("Works!");

그리고 효과가 없습니다. 나는 안타깝게도 인터페이스와 우선적 인 방법에 능숙하지 않습니다 :(. 이유 때문에 다음과 같은 방정식이 있습니다.

x1 + x2 = 0.45
x1 + x4 = 0.2
x2 + x4 = 0.11

더 많은 것이 있으며, 예를 들어 첫 번째 방정식을 두 번째에 추가하고 다른 모든 것을 검색하여 X'es의 조합과 일치하는 것이 있는지 확인하여 추가가 발생합니다.

아마도 내가 완전히 잘못된 방향으로 갈까요?

도움이 되었습니까?

해결책

단일 유형의 경우 아래와 같이 캡슐화하기가 매우 쉽습니다. 열쇠 로서도 불변으로 만들고 싶다는 점에 유의하십시오. 제네릭을 사용하려면 더 어려워집니다 (자세한 정보를 요청) :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
static class Program {
    static void Main() {
        MyVector x = new MyVector(1, 2, 3), y = new MyVector(1, 2, 3),
                 z = new MyVector(4,5,6);
        Console.WriteLine(x == y); // true
        Console.WriteLine(x == z); // false
        Console.WriteLine(object.Equals(x, y)); // true
        Console.WriteLine(object.Equals(x, z)); // false
        var comparer = EqualityComparer<MyVector>.Default;
        Console.WriteLine(comparer.GetHashCode(x)); // should match y
        Console.WriteLine(comparer.GetHashCode(y)); // should match x
        Console.WriteLine(comparer.GetHashCode(z)); // *probably* different
        Console.WriteLine(comparer.Equals(x,y)); // true
        Console.WriteLine(comparer.Equals(x,z)); // false
        MyVector sum = x + z;
        Console.WriteLine(sum);
    }
}
public sealed class MyVector : IEquatable<MyVector>, IEnumerable<int> {
    private readonly int[] data;
    public int this[int index] {
        get { return data[index]; }
    }
    public MyVector(params int[] data) {
        if (data == null) throw new ArgumentNullException("data");
        this.data = (int[])data.Clone();
    }
    private int? hash;
    public override int GetHashCode() {
        if (hash == null) {
            int result = 13;
            for (int i = 0; i < data.Length; i++) {
                result = (result * 7) + data[i];
            }
            hash = result;
        }
        return hash.GetValueOrDefault();
    }
    public int Length { get { return data.Length; } }
    public IEnumerator<int> GetEnumerator() {
        for (int i = 0; i < data.Length; i++) {
            yield return data[i];
        }
    }
    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
    public override bool Equals(object obj)
    {
         return this == (obj as MyVector);
    }
    public bool Equals(MyVector obj) {
        return this == obj;
    }
    public override string ToString() {
        StringBuilder sb = new StringBuilder("[");
        if (data.Length > 0) sb.Append(data[0]);
        for (int i = 1; i < data.Length; i++) {
            sb.Append(',').Append(data[i]);
        }
        sb.Append(']');
        return sb.ToString();
    }
    public static bool operator ==(MyVector x, MyVector y) {
        if(ReferenceEquals(x,y)) return true;
        if(ReferenceEquals(x,null) || ReferenceEquals(y,null)) return false;
        if (x.hash.HasValue && y.hash.HasValue && // exploit known different hash
            x.hash.GetValueOrDefault() != y.hash.GetValueOrDefault()) return false;
        int[] xdata = x.data, ydata = y.data;
        if(xdata.Length != ydata.Length) return false;
        for(int i = 0 ; i < xdata.Length ; i++) {
            if(xdata[i] != ydata[i]) return false;
        }
        return true;        
    }
    public static bool operator != (MyVector x, MyVector y) {
        return !(x==y);
    }
    public static MyVector operator +(MyVector x, MyVector y) {
        if(x==null || y == null) throw new ArgumentNullException();
        int[] xdata = x.data, ydata = y.data;
        if(xdata.Length != ydata.Length) throw new InvalidOperationException("Length mismatch");
        int[] result = new int[xdata.Length];
        for(int i = 0 ; i < xdata.Length ; i++) {
            result[i] = xdata[i] + ydata[i];
        }
        return new MyVector(result);
    }
}

다른 팁

배열 클래스를 연장 할 수 없으며 참조를 참조하십시오. http://msdn.microsoft.com/en-us/library/system.array.aspx

ILIST (기본 방법이 있음)를 구현하거나 클래스에서 배열을 캡슐화하고 전환 연산자를 제공 할 수 있습니다.

자세한 내용이 필요한지 알려주세요.

목록 클래스 만 사용할 수 없습니까? 이것은 이미 AddRange 메소드를 통해 원하는 것을 수행합니다.

구현 ienumerable 상호 작용

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top