I have a generic method behavior of which depends on T is reference type or value type. It looks so:
我有一个泛型方法行为,其依赖于T是引用类型或值类型。它看起来如此:
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?
因为他们的签名是平等的。谁能帮我?
4 个解决方案
#1
67
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:
您可以将typeof运算符与泛型类型一起使用,因此typeof(T)将获得与T对应的Type引用,然后使用IsValueType属性:
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)
#2
6
Type.IsValueType
tells, naturally, if Type
is a value type. Hence, typeof(T).IsValueType
.
当然,Type.IsValueType指示Type是否为值类型。因此,typeof(T).IsValueType。
#3
6
[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.]
[以下答案不检查T的静态类型,而是检查obj的动态类型。这不是你要求的,但是因为它可能对你的问题有用,我会保留这个答案以供参考。]
All value types (and only those) derive from System.ValueType
. Thus, the following condition can be used:
所有值类型(仅限那些)派生自System.ValueType。因此,可以使用以下条件:
if (obj is ValueType) {
...
} else {
...
}
#4
5
try this:
尝试这个:
if (typeof(T).IsValueType)
#1
67
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:
您可以将typeof运算符与泛型类型一起使用,因此typeof(T)将获得与T对应的Type引用,然后使用IsValueType属性:
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)
#2
6
Type.IsValueType
tells, naturally, if Type
is a value type. Hence, typeof(T).IsValueType
.
当然,Type.IsValueType指示Type是否为值类型。因此,typeof(T).IsValueType。
#3
6
[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.]
[以下答案不检查T的静态类型,而是检查obj的动态类型。这不是你要求的,但是因为它可能对你的问题有用,我会保留这个答案以供参考。]
All value types (and only those) derive from System.ValueType
. Thus, the following condition can be used:
所有值类型(仅限那些)派生自System.ValueType。因此,可以使用以下条件:
if (obj is ValueType) {
...
} else {
...
}
#4
5
try this:
尝试这个:
if (typeof(T).IsValueType)