C # Estender tipo de matriz para os operadores de sobrecarga
-
05-07-2019 - |
Pergunta
Eu gostaria de criar minha própria classe estendendo variedade de ints. Isso é possível? O que é preciso matriz de inteiros que podem ser acrescentados pelo operador de "+" para outra matriz (cada um dos elementos adicionado a cada um), e comparados por "==", para que ele poderia (espera-se) ser usado como uma chave no dicionário.
A coisa é que eu não quero implementar a interface IList toda a minha nova classe, mas apenas adicionar esses dois operadores para a aula matriz existente.
Eu estou tentando fazer algo como isto:
class MyArray : Array<int>
Mas ele não está funcionando dessa maneira, obviamente;).
Desculpe se eu sou claro, mas eu estou procurando solução para horas agora ...
UPDATE:
Eu tentei algo parecido com isto:
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;
}
}
Em seguida, usá-lo como este:
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!");
E nenhum efeito. Eu não sou bom com interfaces e métodos de substituição infelizmente :( Quanto razão que eu estou tentando fazer isso eu tenho algumas equações como:..
x1 + x2 = 0,45
x1 + x4 = 0,2
x2 + x4 = 0,11
Há muito mais deles, e eu preciso, por exemplo, adicionar primeira equação para a segunda e pesquisar todos os outros para descobrir se há algum que corresponda à combinação de x'es, resultando em que a adição.
Talvez eu estou indo na direção totalmente errada?
Solução
Para um único tipo, é muito fácil para encapsular, como abaixo. Note-se que como uma chave que você deseja torná-lo imutável também. Se você quiser usar os genéricos, fica mais difícil (pedir mais info):
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);
}
}
Outras dicas
Não é permitido estender a classe array, consulte a referência: http : //msdn.microsoft.com/en-us/library/system.array.aspx
Você poderia implementar IList (que tem os métodos básicos), ou encapsular uma matriz em sua classe e fornecer aos operadores de conversão.
Por favor, deixe-me saber se você precisa de mais detalhes.
Você pode não apenas usar a classe Lista? Isso já faz o que quiser através do método AddRange.
IEnumerable Interface