我有一個方法,它采用任意型別的陣列。我有一個物件陣列(在我的例子中,這是一個帶有變數的類)。然后我把我的物件陣列放在這個方法中。那么如何使用這個物件的變數呢?
public class C // This one of my classes
{
public int I { get; set; }
}
public static void Sort<T>(T[] array, string name) // Here i put my class as argument
{
...
Array.Sort<T>(array, (a, b) => a.I.CompareTo(b.I)); // Here "I" is some variable in my class, which i need to use
...
}
static void Main(string[] args) // Here i create an array of classes
{
...
C[] classes = new C[100000];
Sort(classes);
...
}
uj5u.com熱心網友回復:
我建議你在你的類中實作IComparable<T>介面,你甚至不需要專門的排序方法
請考慮以下示例代碼
using System;
using System.Collections.Generic;
namespace Test
{
class Comparable : IComparable<Comparable>
{
public int Number { get; set; }
public int CompareTo(Comparable other)
{
if (other == null)
return 1;
return Number.CompareTo(other.Number);
}
}
class Program
{
static void Main()
{
List<Comparable> comparableList = new List<Comparable>
{
new Comparable { Number = 75 },
new Comparable { Number = 1 },
new Comparable { Number = 23 }
};
comparableList.Sort();
foreach (Comparable comparable in comparableList)
Console.WriteLine(comparable.Number);
}
}
}
uj5u.com熱心網友回復:
這是你想要的嗎?
public class C
{
public int I { get; set; }
}
public class CComparer : IComparer<C>
{
public int Compare(C x, C y)
{
return x.I.CompareTo(y.I);
}
}
static class Program
{
static void Main(string[] args)
{
var array = new C[100];
// Calls CComparer.Compare(x,y);
Array.Sort(array, new CComparer());
}
}
一個替代版本是
public class C
{
public int I { get; set; }
public static IComparer<C> Comparer { get; } = new CComparer();
class CComparer : IComparer<C>
{
internal CComparer() { }
public int Compare(C x, C y)
{
return x.I.CompareTo(y.I);
}
}
}
static class Program
{
static void Main(string[] args)
{
var array = new C[100];
Array.Sort(array, C.Comparer);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385969.html
上一篇:列等于身份主鍵值的物體添加/插入
