开发者

Nullable<T> as a parameter

I alredy have this:

public static object GetDBValue(object ObjectEvaluated)
 {
  if (ObjectEvaluated == null)
   return DBNull.Value;
  else
   return ObjectEvaluated;
 }
used like:

 List<SqlParameter> Params = new List<SqlParameter>();
 Params.Add(new SqlParameter("@EntityType", GetDBValue(EntityType)));

Now i wanted to keep the same interface but extend that to use it with nullable

 public static object GetDBValue(int? ObjectEvaluated)
 {
  if (ObjectEvaluated.HasValue)
   return ObjectEvaluated.Value;
  else
   return DBNull.Value;
 }

 public static object GetDBValue(DateTime? ObjectEvaluated)
 {...}

but i want only 1 function GetDBValue for nullables. How do I do that and keep the call as is is? Is that possible at all?

I can make it work like:

 public static object GetDBValue<T>(Nullable<T> ObjectEvaluated) where T : struct
 {
  if (ObjectEvaluated.HasValue)
   return ObjectEvaluated.Value;
 开发者_开发问答 else
   return DBNull.Value;
 }

But the call changes to:

Params.Add(new SqlParameter("@EntityID ", GetDBValue<int>(EntityID)));


The generic version that you have is fine, although you can shorten it even more with the null-coalescing operator:

public static object GetDBValue<T>(Nullable<T> ObjectEvaluated)
    where T : struct
{
    return ObjectEvaluated ?? (object)DBNull.Value;
}

What you might be missing is that you don't need to use the generic parameter when you call it; C#'s type inference will figure it out for you:

int? x = null;
object y = GetDBValue(x);


If EntityID (in your last example) is a Nullable type then the compiler will know to call GetDBValue without specifying the underlying type.


I'm not sure there is much point doing that; what you have already boxes (since it returns object), you might as well let the CLR do that for you. Simply:

public static object GetDBValue(object ObjectEvaluated)
{
  return ObjectEvaluated ?? DBNull.Value;
}

There isn't much benefit adding generics here (since we don't use the T).

You certainly could add a generic method, but what does it add?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜