restrict T to a int value?
How can i solve this error msg?
static publi开发者_运维百科c class Blah
{
public static T val<T>(this bool b, T v) { return b == true? v:0; }
}
error
Type of conditional expression cannot be determined because there is no implicit conversion between 'T' and 'int
If you want T to be an int, accept an int and not a T. Otherwise, consider returning default(T) if b == false.
return b ? v : default(T);
If T is an int, it will return 0. If it is a reference type, it will be null. And on and on..
Why are you trying to use generics if you only want an int?
// No need to compare b to true...
public static int val(this bool b, int v) { return b ? v : 0; }
Otherwise, use default(T)
as others have mentioned.
public static T val<T>(this bool b, T v) { return b ? v : default(T); }
default(T)
will default to 0 for int
s and other numeric values, false
for bool
s, null
for objects...
If you want to return the "default" value for T:
public static T val<T>(this bool b, T v) { return b == true? v : default(T); }
Default Values Table
default Keyword in Generic Code
There is no way to do this in C#. You can do
where T: struct
, and force T to be a value type, but that still isn't enough.
Or you can do
default(T)
, which is 0 when T is an int.
Try replacing v : 0
with v : default(T)
, if you have a good reason for generics. If you need to restrict it to int, then you're not writing a generic class.
If there's only valid type for T then it shouldn't be generic:
public static int val(this bool b, int v)
{
return b ? v : 0;
}
If you want this to work for any value type you could do this:
public static int val<T>(this bool b, T v) where T : struct
{
return b ? v : default(T);
}
Srsly!
To "restrict T to int" you take advantage of a special compiler feature known as strong-typing
:
static public class Blah
{
public static int val(this bool b, int v) { return b == true? v:0; }
}
Tada! :)
Seriously, why are you using generics?
精彩评论