如何确定T是泛型中的值类型还是引用类? [英] How to determine whether T is a value type or reference class in generic?

查看:50
本文介绍了如何确定T是泛型中的值类型还是引用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型方法,其行为取决于T是引用类型还是值类型.看起来是这样的:

I have a generic method behavior of which depends on T is reference type or value type. It looks so:

T SomeGenericMethod <T> (T obj)
{
  if (T is class) //What condition I must write in the brackets?
   //to do one stuff
  else //if T is a value type like struct, int, enum and etc.
   //to do another stuff
}

我无法像这样重复此方法

I can't duplicate this method like:

T SomeGenericMethod <T> (T obj) where T : class
{
 //Do one stuff
}

T SomeGenericMethod <T> (T obj) where T : struct
{
 //Do another stuff
}

因为他们的签名是相等的.谁能帮我吗?

because their signatures are equal. Can anyone help me?

推荐答案

您可以使用 IsValueType 属性:

You can use the typeof operator with generic types, so typeof(T) will get the Type reference corresponding to T, and then use the IsValueType property:

if (typeof(T).IsValueType)

或者如果您想包括可为空的值类型,就像它们是引用类型一样:

Or if you want to include nullable value types as if they were reference types:

// Only true if T is a reference type or nullable value type
if (default(T) == null)

这篇关于如何确定T是泛型中的值类型还是引用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆