這是針對通用bubbleSorter我的Java代碼:轉換Java泛型到C#泛型
public class BubbleSorter<E extends Comparable<E>> {
E[] a;
void swap(int i, int j) {
E temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void bubbleSort(E[] a) {
this.a=a;
for (int i=0 ;i<a.length;i++) {
for (int j=0;j<a.length;j++) {
if (a[i].compareTo(a[j]) > 0) swap(i,j);
}
}
}
}
public interface Comparable<E> {
public int compareTo(E e);
}
,這裏是使用它的一個例子:
public class Test {
public static void main (String arg[]) {
Rational[] a = new Rational[3];
a[0]=Rational.rationalFactory(9,2);
a[1]=Rational.rationalFactory(1,3);
a[2]=Rational.rationalFactory(10,11);
Complex[] b = new Complex[3];
b[0]=new Complex(7,5);
b[1]=new Complex(3,4);
b[2]=new Complex(8,9);
BubbleSorter<Rational> br=new BubbleSorter<Rational>();
BubbleSorter<Complex> bi=new BubbleSorter<Complex>();
br.bubbleSort(a);
bi.bubbleSort(b);
for (int i=0 ; i < 3 ; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
for (int i=0 ; i < 3 ; i++) {
System.out.print(b[i] + " ");
}
}
}
public class Rational implements Comparable<Rational> {
int mone,mehane;
private Rational(int n,int m) {
mone=n;
mehane=m;
}
static public Rational rationalFactory(int n,int m) {
if (n==0) return null;
return new Rational(n,m);
}
public String toString() {
return mone + "/" + mehane;
}
public int compareTo(Rational r) {
return (r.mehane*mone - r.mone*mehane);
}
}
public class Complex implements Comparable<Complex> {
int real,img;
public Complex(int r,int i) {
real=r;
img=i;
}
public String toString() {
return real + "+" + img + "i";
}
public int compareTo(Complex r) {
double x=(getLength() - r.getLength());
if (x>0) return 1;
if (x==0) return 0;
return -1;
}
public double getLength() {
return Math.sqrt(real*real+img*img);
}
}
當我試圖將我的Java代碼到C#,我卡住試圖強制泛型類型擴展比較自<電子郵件:比較>不起作用。我如何克服這一點?
這是我的嘗試:
abstract class Comparable<E> {
static bool operator ==(Comparable<E> e1, Comparable<E> e2);
static bool operator !=(Comparable<E> e1, Comparable<E> e2) {
return !(e1 == e2);
}
static bool operator >(Comparable<E> e1, Comparable<E> e2);
static bool operator >=(Comparable<E> e1, Comparable<E> e2) {
if (e1 > e2) return true;
if (e1 == e2) return true;
return false;
}
static bool operator <=(Comparable<E> e1, Comparable<E> e2) {
return !(e1 > e2);
}
static bool operator <(Comparable<E> e1, Comparable<E> e2) {
return !(e1 >= e2);
}
}
public class BubbleSorter<E : Comparable<E>> {
E[] a;
void swap(int i, int j) {
E temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void bubbleSort(E[] a) {
this.a=a;
for (int i=0 ;i<a.length;i++) {
for (int j=0;j<a.length;j++) {
if (a[i]>a[j]) swap(i,j);
}
}
}
}
我在努力學習。就這樣。 –