.net - What is the implicit contract for a property's type when used with the ConfigurationProperty attribute? -
as example, serialize , deserialize system.version
object part of application's custom configuration section. attempting following property declaration:
public class configelement : configurationelement { [configurationproperty("ver", isrequired = false, defaultvalue = "1.2.4.8")] public version ver { { return (version)this["ver"]; } set { this["ver"] = value; } } }
unfortunately, attempting serialize or use property (with or without defaultvalue
) yields following exception message.
system.configuration.configurationerrorsexception : value of property 'ver' cannot converted string. error is: unable find converter supports conversion to/from string property 'ver' of type 'version'.
system.version.tostring()
writes object well-known string format consumable system.version.ctor(string)
, seems feasible "converter" exist type. comparably, system.timespan
type has similar methods , functions (parse
in-place of .ctor(string)
) , type works configuration system (a converter must exist).
how know if type has suitable converter? contract (implicit or otherwise) must such type satisfy?
for configurationproperty work, type used must associated typeconverter knows how convert string. configurationproperty have converter property, alas, it's read-only. and, that's bad luck, version not have implicit typeconverter declared either.
what can though, add typeconverterattribute version class programmatically, , work around these issues. need call line once in program before accessing configuration:
typedescriptor.addattributes(typeof(version), new typeconverterattribute(typeof(versiontypeconverter))); // ... can call configuration code now...
with following custom-made versiontypeconverter:
public class versiontypeconverter : typeconverter { public override object convertfrom(itypedescriptorcontext context, cultureinfo culture, object value) { return new version((string)value); } public override bool canconvertfrom(itypedescriptorcontext context, type sourcetype) { if (sourcetype == typeof(string)) return true; return base.canconvertfrom(context, sourcetype); } }
Comments
Post a Comment