c# - Constrain generic to be a nullable type -
i'm looking sample usage this:
foo<string> stringfoo = new foo<string>("the reply is"); foo<int> intfoo = new foo<int>(42); // value of intfoo & stringfoo typed stringfoo.nullify(); intfoo.nullify(); if (stringfoo == null && intfoo == null) messagebox.show("both null);
given class foo, can auto-wrap t nullable:
public class foo1<t> t : struct { private t? _value; public foo(t? initvalue) { _value = initvalue; } public t? value { { homecoming _value; } } public void nullify { _value = null; } }
this works primitives, not string or other classes.
next flavor works strings, not primitives:
public class foo2<t> { private t _value; public foo(t initvalue) { _value = initvalue; } public t value { { homecoming _value; } } public void nullify { _value = default(t); } }
i utilize nullable<int>
foo2 , code work this:
foo2<int?> intfoo = new foo<int?>(42);
but error prone because fails foo2. if constrain t types back upwards nullability fine.
so after of that, there way constrain t nullable type?
some additional notes: .net 4.0, vs2010. , did find 1 similar question on here, without succesful answer.
you might able create constructor of foo<t>
internal, , require new instances can created through mill class:
public class foo<t> { private t value; internal foo(t value) { this.value = value; } public void nullify() { this.value = default(t); } public t value { { homecoming this.value; } } } public class foo { public static foo<t> create<t>(t value) t : class { homecoming new foo<t>(value); } public static foo<t?> create<t>(t? value) t : struct { homecoming new foo<t?>(value); } }
c# .net generics
No comments:
Post a Comment