How to determine whether T is a value type or refe

2020-05-24 18:51发布

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?

标签: c# .net generics
5条回答
Summer. ? 凉城
2楼-- · 2020-05-24 19:31

try this:

if (typeof(T).IsValueType)
查看更多
手持菜刀,她持情操
3楼-- · 2020-05-24 19:32

[The following answer does not check the static type of T but the dynamic type of obj. This is not exactly what you asked for, but since it might be useful for your problem anyway, I'll keep this answer for reference.]

All value types (and only those) derive from System.ValueType. Thus, the following condition can be used:

if (obj is ValueType) {
    ...
} else {
    ...
}
查看更多
老娘就宠你
4楼-- · 2020-05-24 19:39

I'm late to the party, but I just stumbled on this. So as of determining if it's a Reference-Type,

typeof(T).IsClass

respectively

obj.GetType().IsClass

could work (.net 4.7+ , not checked on former Versions)

查看更多
欢心
5楼-- · 2020-05-24 19:48

Type.IsValueType tells, naturally, if Type is a value type. Hence, typeof(T).IsValueType.

查看更多
贪生不怕死
6楼-- · 2020-05-24 19:53

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)
查看更多
登录 后发表回答