Is there any way to constrain a type parameter to EITHER a reference type OR a nullable value type?
It'd be nice if I could define a method like this:
public T GetItem<T>() where T : null
{
if (someCondition<T>())
return someCalculation<T>();
else
return null;
}
Then I could use this on reference types (e.g., object
, string
) as well as nullable value types (e.g., int?
, double?
): anything that can be assigned to null
. But this isn't possible.
Then again, for all I know, maybe it is? I know there'a no 开发者_如何学Cnull
constraint like I just fantasized about; but is there some workaround or clever way of accomplishing this that just hasn't occurred to me?
Personally, I would create two overloaded generic methods: one that accepts reference types and another that accepts nullable value types. Then you'll be able to call with either kind of parameter.
I used to never use output parameters, partly I think the syntax just felt clumsy. However, a few years ago I started using them more and they've become a common aspect of the code that I write.
I think this is the kind of function where I would really consider writing the function with an output parameter and a boolean return type, as shown below:
public bool GetItem<T>(out T value)
{
if (someCondition<T>())
{
value = someCalculation<T>();
return true;
}
else
{
value = default(T);
return false;
}
}
With this approach there is no need to restrict your generic parameter to reference type or a nullable type.
As I mentioned above, I originally felt that output parameter syntax was clumsy, but after I really started using it frequently I felt that the code that consumed my functions with output parameters was actually more accurate towards representing the problem that I was trying to solve, if that makes any sense.
It would depend on the generic usage in the someCondition
and someCalculation
methods. But this sounds like where the 'default' keyword could be used.
return default(T);
精彩评论