c# - static information in a class -
i couple of classes have way of telling me how many fields in them, , enforce classes have through inheritance, this:
// code not compile abstract class base { abstract static const int fieldcount = -1 } class node : base { int x, y, z; // has 3 fields, so: override static const int fieldcount = 3; } class way : base { int w, x, y, z; // has 4 fields, so: override static const int fieldcount = 4; } i cannot working, not interface or abstract base class. need information available type, not through actual instance of class (therefore static).
class enumerabledatareader<tsource> : idatareader tsource : base { public int fieldcount { { return tsource.fieldcount <- access static info, not work } } } is there way that, or here reflection way go?
thanks!
doesn't there real need use fields here, if switched using properties instead override property implementation on each derivation i.e.
abstract class base { public static int fieldcount { { return -1; } } } class node : base { int x, y, z; // has 3 fields, so: public new static int fieldcount { { return 3; } } } class way : base { int w, x, y, z; // has 4 fields, so: public new static int fieldcount { { return 4; } } } ... console.writeline(base.fieldcount) // -1 console.writeline(node.fieldcount) // 3 console.writeline(way.fieldcount) // 4 to solve other half of problem, need rely on reflection i.e.
class enumerabledatareader<tsource> tsource : base { public int fieldcount { { return (int)typeof(tsource).getproperties().single(x => x.name == "fieldcount").getvalue(null); } } } ... var reader = new enumerabledatareader<node>(); console.writeline(reader.fieldcount); // 3
Comments
Post a Comment