C# generic constraint for Type to be castable -
is there way c# generics limit type t castable type?
example:
lets saving information in registry string
, , when restore information have function looks that:
static t getobjectfromregistry<t>(string regpath) t castable string { string regvalue = //getting regisstry value... t objectvalue = (t)regvalue; return objectvalue ; }
there no such type of constraints in .net. there 6 types of constraints available (see constraints on type parameters):
where t: struct
type argument must value typewhere t: class
type argument must reference typewhere t: new()
type argument must have public parameterless constructorwhere t: <base class name>
type argument must or derive specified base classwhere t: <interface name>
type argument must or implement specified interfacewhere t: u
type argument supplied t must or derive argument supplied u
if want cast string type, can casting object first. can't put constraint on type parameter make sure casting can occur:
static t getobjectfromregistry<t>(string regpath) { string regvalue = //getting regisstry value... t objectvalue = (t)(object)regvalue; return objectvalue ; }
another option - create interface:
public interface iinitializable { void initfrom(string s); }
and put constraint:
static t getobjectfromregistry<t>(string regpath) t: iinitializable, new() { string regvalue = //getting regisstry value... t objectvalue = new t(); objectvalue.initfrom(regvalue); return objectvalue ; }
Comments
Post a Comment