(Gast)
n/a Beiträge
|
Re: [.NET] Generics und Operatorüberladung
10. Jul 2009, 22:10
Ein Beispiel für beides:
Code:
interface IArithmetic<T, V>
{
T Add(T left, T right);
V Value {
get;
set;
}
}
struct DoubleArithmetic : IArithmetic<DoubleArithmetic, double>
{
public double Value {
get;
set;
}
public DoubleArithmetic Add(DoubleArithmetic left, DoubleArithmetic right)
{
return new DoubleArithmetic { Value = left.Value + right.Value };
}
public static implicit operator DoubleArithmetic(double value)
{
return new DoubleArithmetic { Value = value };
}
public static implicit operator double(DoubleArithmetic da)
{
return da.Value;
}
}
class Combiner<T>
{
public Func<T, T, T> Add {
get;
private set;
}
public Combiner(Func<T, T, T> _add)
{
Add = _add;
}
}
public class MainClass
{
static void test<T, V>(V inc) where T : IArithmetic<T, V>, new()
{
var d = DateTime.Now;
T da = new T();
int max = 10000000;
for (int i = 0; i < max; i++) {
da = da.Add(da, new T { Value = inc });
}
Console.WriteLine((DateTime.Now - d).TotalMilliseconds / max * 1000000);
}
static void test2<T>(T inc, Combiner<T> ops) where T: new()
{
var d = DateTime.Now;
T da = new T();
int max = 10000000;
for (int i = 0; i < max; i++) {
da = ops.Add(da, inc);
}
Console.WriteLine((DateTime.Now - d).TotalMilliseconds / max * 1000000);
}
public static void Main(string[] args)
{
test<DoubleArithmetic, double>(1.0);
test2<double>(1.0, new Combiner<double>((a, b) => a + b));
}
}
Wobei ich die Delegate-Variante im Nachhinein doch eleganter finde. Schneller ist sie auch, was mich nicht sehr wundert
|
|
Zitat
|