我有一个泛型方法行为,其依赖于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
}
Run Code Online (Sandbox Code Playgroud)
我不能复制这个方法,如:
T SomeGenericMethod <T> (T obj) where T : class
{
//Do one stuff
}
T SomeGenericMethod <T> (T obj) where T : struct
{
//Do another stuff
}
Run Code Online (Sandbox Code Playgroud)
因为他们的签名是平等的.谁能帮我?
Jon*_*eet 82
您可以将typeof运算符与泛型类型一起使用,因此typeof(T)将获得Type对应的引用T,然后使用该IsValueType属性:
if (typeof(T).IsValueType)
Run Code Online (Sandbox Code Playgroud)
或者,如果要包含可空值类型,就好像它们是引用类型一样:
// Only true if T is a reference type or nullable value type
if (default(T) == null)
Run Code Online (Sandbox Code Playgroud)
[以下答案不检查静态类型T但动态类型obj.这不正是你问什么,但因为它可能是你的问题很有用,无论如何,我会保持这个答案以供参考.]
所有值类型(仅限于那些)派生自System.ValueType.因此,可以使用以下条件:
if (obj is ValueType) {
...
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
我参加聚会迟到了,但我只是偶然发现了这一点。因此,在确定它是否是引用类型时,
typeof(T).IsClass
Run Code Online (Sandbox Code Playgroud)
分别
obj.GetType().IsClass
Run Code Online (Sandbox Code Playgroud)
可以工作(.net 4.7+,未在以前的版本上检查)
| 归档时间: |
|
| 查看次数: |
16364 次 |
| 最近记录: |