Pregunta

Me gustaría crear mi propia clase que amplíe la matriz de entradas ¿Es eso posible? Lo que necesito es una matriz de entradas que se pueden agregar con " + " operador a otra matriz (cada elemento agregado a cada uno), y comparado por " == " ;, por lo que podría (con suerte) usarse como una clave en el diccionario.

La cuestión es que no quiero implementar toda la interfaz IList en mi nueva clase, sino solo agregar esos dos operadores a la clase de matriz existente.

Estoy tratando de hacer algo como esto:

class MyArray : Array<int>

Pero obviamente no funciona de esa manera;).

Lo siento si no estoy claro, pero estoy buscando la solución durante horas ...

ACTUALIZACIÓN:

Intenté algo como esto:

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;
    }

}

Entonces úsalo así:

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!");

Y sin efecto. Desafortunadamente, no soy bueno con las interfaces y los métodos de anulación :(. Por lo que estoy tratando de hacerlo. Tengo algunas ecuaciones como:

x1 + x2 = 0,45
x1 + x4 = 0.2
x2 + x4 = 0.11

Hay muchos más, y necesito, por ejemplo, agregar la primera ecuación a la segunda y buscar todas las demás para averiguar si hay alguna que coincida con la combinación de x'es que resulta en esa suma.

¿Tal vez estoy yendo en la dirección totalmente equivocada?

¿Fue útil?

Solución

Para un solo tipo, es bastante fácil encapsular, como se muestra a continuación. Tenga en cuenta que, como clave, también desea que sea inmutable. Si desea usar genéricos, se vuelve más difícil (solicite más información):

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);
    }
}

Otros consejos

No está permitido extender la clase de matriz, consulte la referencia: http : //msdn.microsoft.com/en-us/library/system.array.aspx

Puede implementar IList (que tiene los métodos básicos) o encapsular una matriz en su clase y proporcionar operadores de conversión.

Avíseme si necesita más detalles.

¿No puedes simplemente usar la clase List? Esto ya hace lo que quiere a través del método AddRange.

implemente el ienumerable interfaz

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top