[英]How to determine whether T is a value type or reference class in generic?
I have a generic method behavior of which depends on T is reference type or value type.我有一个泛型方法的行为取决于 T 是引用类型还是值类型。 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?
谁能帮我?
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:或者,如果您想包含可为 null 的值类型,就好像它们是引用类型一样:
// Only true if T is a reference type or nullable value type
if (default(T) == null)
[The following answer does not check the static type of T
but the dynamic type of obj
. [以下答案不检查
T
的静态类型,而是检查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
.所有值类型(并且仅那些)派生自
System.ValueType
。 Thus, the following condition can be used:因此,可以使用以下条件:
if (obj is ValueType) {
...
} else {
...
}
Type.IsValueType
tells, naturally, if Type
is a value type. Type.IsValueType
自然会告诉Type
是否是值类型。 Hence, typeof(T).IsValueType
.因此,
typeof(T).IsValueType
。
试试这个:
if (typeof(T).IsValueType)
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)可以工作(.net 4.7+,未检查以前的版本)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.