casting - How to define cast operator in super class in C# 3.5? -
i have container class adding properties standard data types int, string , on. container class encapsulate object of such (standard type) object. other classes use sub classes of container class getting/setting added properties. want sub classes can implicitly cast between encapsulated objects , without having code in it.
here simplified example of classes:
// container class encapsulates strings , adds property tobechecked // , should define cast operators sub classes, too. internal class stringcontainer { protected string _str; public bool tobechecked { get; set; } public static implicit operator stringcontainer(string str) { return new stringcontainer { _str = str }; } public static implicit operator string(stringcontainer container) { return (container != null) ? container._str : null; } } // example of many sub classes. code should short possible. internal class subclass : stringcontainer { // want avoid following cast operator definition // public static implicit operator subclass(string obj) // { // return new subclass() { _str = obj }; // } } // short code demosntrate usings of implicit casts. internal class mainclass { private static void main(string[] args) { subclass subclass = "test string"; // error: cannot convert source type 'string' 'subclass' string teststring = subclass; // no error } }
my real container class has 2 type parameters, 1 type of encapsulated object (string, int,...) , second sub class type (e.g. subclass).
how can make code
subclass subclass = "test string"; // error: cannot convert source type 'string' 'subclass'
runnable minimal code in sub classes?
i don't think there way define conversion operator in base class.
the base class doesn't know sub class, doesn't have enough information construct it. example, if subclass
type had constructor requires arguments? base class doesn't know sub class, cannot construct in way.
maybe use way parameterize stringcontainer
type. example, instead of using implementation inheritance (sub classes), instead pass functions (delegates of type func<...>
) stringcontainer
class. way, user parameterize class , implicit conversion still work.
Comments
Post a Comment