inheritance - Static interface equivalent C# -
i've worked singletons in past , i'm aware it's solution people trying solve static interface problem. in case, can't use singleton because have external class i'm inheriting , have no control on 1 (a library).
basically, have many classes inheriting "tablerow" (the class in library) , need every single of these classes implement static method (ex: getstaticidentifier). eventually, need store these objects in 1 of base types, , use static method on specific type.
my question, there solution using singleton? there feature i'm not aware of in c# me solve problem?
it seems want supply meta-information along subclasses of tablerow; meta-information can retrieved without instantiating particular subclass.
while .net lacks static interfaces , static polymorphism, can (to extent, see below) solved custom attributes. in other words, can define custom attribute class stores information want associate type:
[attributeusage(attributetargets.class, inherited = false, allowmultiple = false)] public class staticidentifierattribute : attribute { public staticidentifierattribute(int id) { this.staticidentifier = id; } private readonly int staticidentifier; public int staticidentifier { { return staticidentifier; } } } you can apply custom attribute tablerow subclasses:
[staticidentifier(42)] public class mytablerow : tablerow { // ... } you can retrieve type instance mytablerow (or other subclass of tablerow) , use getcustomattributes method retrieve staticidentifierattribute instance , read out value stored in itsstaticidentifier` property class.
the drawback compared static interfaces , static polymorphism is not compile-time ensured each tablerow subclass has attribute; have catch (and either throw exception, or ignore respective tablerow subclass) @ runtime.
moreover, cannot ensure attribute only applied tablerow subclasses, then, while may bit untidy, doesn't matter (if applied class, not have effect there, no code ever processes other classes).
Comments
Post a Comment