Monday 15 April 2013

c# - Excluding Types in the Generic Constraints (Possible?) -



c# - Excluding Types in the Generic Constraints (Possible?) -

is possible exclude specific types set of possible types, can used in generic parameter? if how.

for example

foo<t>() : t != bool

would mean type except type bool.

edit

why?

the next code effort enforce negative constraint.

using system; using system.collections.generic; using system.linq; using system.text; namespace consoleapplication1 { class programme { static void main(string[] args) { var x1=lifted.lift("a"); var x2=lifted.lift(true); } static class lifted { // 1 "exclude" inferred type variant of parameter [obsolete("the type bool can not lifted", true)] static public object lift(bool value) { throw new notsupportedexception(); } // 1 "exclude" variant generic type specified. [obsolete("the type bool can not lifted", true)] static public lifted<t> lift<t>(bool value) { throw new notsupportedexception(); } static public lifted<t> lift<t>(t value) { homecoming new lifted<t>(value); } } public class lifted<t> { internal readonly t _value; public t value { { homecoming this._value; } } public lifted(t value) { _value = value; } } } }

as can see involves bit of faith in overload resolution beingness correct, , bit of @jonskeet -esque evil code.

comment out section deals inferred type illustration , doesn't work.

it much improve have excluded generic constraint.

nope, can't create one-off exclusions using type constraints. can @ runtime though:

public void foo<t>() { if (typeof(t) == typeof(bool)) { //throw exception or handle appropriately. } }

c# .net generics constraints

No comments:

Post a Comment