The example I am giving is not exactly what I'm working on, but its is an approximate representation and greatly simplified to the exact problem. I am willing to investigate all options.
I have an abstract class with a data value I want to override in a subsequent class.
The base abstract class
public abstract class Variable
{
public abstract long data;
}
I have a subclass
public class FloatVariable : Variable
{
public override float data;
}
However when using late dynamic binding I have trouble
Variable var = new FloatVariable();
var.data = 0.33f;
Causes an error that it "Cannot implicitly convert type 'float' to 'long'"
Obviously I'm not doing it right, however if th开发者_运维百科ere is a way to override variables (and types) so that late dynamic binding will still allow it to compile, it would make my life infinity easier.
You may be better off using generics:
public class Variable<T>
{
public T data;
}
then you can do
Variable var = new Variable<float>();
var.data = 0.33f;
From http://msdn.microsoft.com/en-us/library/ebca9ah3(v=vs.80).aspx:
"An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override."
So, you can't change the type from long to float.
I found a solution that solves my problem that I could not resolve with generics/templates.
Create a new scalar class
Class Scalar
{
private byte dataByte = 0;
private short dataShort = 0;
// ... int, long, float, double
private string dataString = 0;
private List<Variable> dataList = null;
//constructors for "later" type casting (see below)
public Scalar(byte data)
{
this.dataByte = data;
}
//* repeat this for short, int, long, float, double, string, List<>
//implicit conversions for getting data out
public static implicit operator byte(Scalar scalar)
{
return scalar.dataByte;
}
//* repeat this for short, int, long, float, double, string, List<>
//implicit conversions for getting data in (invokes a constructor)
public static implicit operator Scalar(byte data)
{
return new Scalar(data);
}
//* repeat this for short, int, long, float, double, string, List<>
}
Then create my base variable class
abstract class Variable
{
public Scalar Data
{
get { return data; }
set { data = value; }
}
protected Scalar data = new Scalar(0);
/* other meta information etc */
}
Then create your sub classes of your meta variables
class MetaByte : Variable
{
public byte Data
{
get { return data; }
set { data = value; }
}
/* byte specific features */
}
Then using it works just fine with dynamic binding
Variable scalar = new MetaByte();
scalar.Data = 33;
scalar = new MetaList();
scalar.Data = new List<Variable>();
Its not perfect with the lists, but it seems to work for how I intend to use it.
精彩评论