如何检查泛型方法参数是否为值类型? [重复]

时间:2022-09-21 00:41:50

This question already has an answer here:

这个问题在这里已有答案:

Is there a way to check if a variable is value type of reference type?

有没有办法检查变量是否是引用类型的值类型?

Imagine:

想像:

private object GetSomething<T>(params T[] values) 
{
    foreach (var value in values)
    {
        bool is ValueType; // Check if 'value' is a value type or reference type
    }
}

2 个解决方案

#1


16  

bool isValueType = typeof(T).IsValueType;

Job done... it doesn't matter if any of the values is null, and it works even for an empty array.

完成任务...如果任何值为null,则无关紧要,即使对于空数组也是如此。

#2


0  

Your condition will look like

你的病情会是这样的

var cond = false;
if(value != null) 
  cond = value.GetType().IsValueType

#1


16  

bool isValueType = typeof(T).IsValueType;

Job done... it doesn't matter if any of the values is null, and it works even for an empty array.

完成任务...如果任何值为null,则无关紧要,即使对于空数组也是如此。

#2


0  

Your condition will look like

你的病情会是这样的

var cond = false;
if(value != null) 
  cond = value.GetType().IsValueType