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 type
  • where t: class type argument must reference type
  • where t: new() type argument must have public parameterless constructor
  • where t: <base class name> type argument must or derive specified base class
  • where t: <interface name> type argument must or implement specified interface
  • where 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

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -