Using of static virtual generic methods
My question is: how to simple write measure classes? For example, i want
to write classes for Length, so for ex. it will be Meters and Diums. It's
clear enough that dium == 0.0254 meters, and for every instance of Dium
class it will be true. So it's clear that field LengthOfItem (returning
count of meters in one unit) should be static. But i don't know a priori
this value, so it could also be abstract/virtual. But static fields cannot
be virtual. Or can? If you think about it, classes are just instances,
inherited from Type or something like this, it mean classes are specials
singletons object, so logicaly they can inherit something too. For example
i want to write a class Human and inherit it by classes Man and Woman, so
Human has abstract bool HasTits {get;} It's clear enough that it's a
property of class, not of an instance. Okay, i can call this method. But
if i need to call it from base class, for example in the class Human i'm
writing something like this
void Foo<T>() where T: Human // T is Man or Woman
{
var t = typeof (T);
var fieldvalue = t.GetStaticProperty("HasTits");
//working with value
}
but what should i write?
Let's return to our situation. I'm writing a code like this:
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ConsoleApplication119
{
public abstract class Length<T> where T : Length<T>
{
public double Count { get; private set; }
protected static double LengthOfItem;
static Length()
{
RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
}
protected Length(double count)
{
Count = count;
}
public double Meters
{
get
{
return Count*LengthOfItem;
}
}
public Length<T> ConvertTo<T>() where T : Length<T>
{
double count = Count * LengthOfItem / Length<T>.LengthOfItem;
var constructor = typeof (T).GetConstructors().Single(info =>
info.GetParameters().Length == 1);
return (Length<T>) constructor.Invoke(new object[] {count});
}
}
class Meter : Length<Meter>
{
public Meter(double count) : base(count)
{
}
static Meter()
{
LengthOfItem = 1;
}
}
class Dium :Length<Dium>
{
public Dium(double count) : base(count)
{
}
static Dium()
{
LengthOfItem = 0.0254;
}
}
class Program
{
static void Main()
{
var meters = new Meter(5);
var diums = meters.ConvertTo<Dium>();
Console.WriteLine(diums.Count);
Console.ReadKey();
}
}
}
it works fine, but i dislike my method ConvertTo. And static constructors.
They allows to make static virtual field, but they enlarge my code and
make it ugly and complex. And it uses reflection. Imo using reflection and
crutches signify that something is bad. How can i improve it?
P.S. A little question, so little that doesn't require another topics,
let's take a look on this
public abstract class Length<T> where T : Length<T>
isn't this definition recursive, it mean T could be
Length<Length<Length<Length<...>>>> or not?
No comments:
Post a Comment