我怎样才能保证T是班级?

时间:2012-01-24 13:08:55

标签: c# .net generics

我有下一个代码:

public static T GetSerializedCopy<T> (T src)
{
  //some code to obtain a copy
}

我如何保证T将成为一个类,而不是结构或枚举或其他东西?

5 个答案:

答案 0 :(得分:21)

常见错误(请参阅此处的答案)认为将where T : class添加到泛型方法/类型声明可实现此目的 - 但这是错误的。这个实际上意味着“T必须是一个引用类型”,它也包括代理和接口(加上数组,以及像string这样的东西)。

如果你想上课,有两种方法;最简单的是坚持where T : class, new(),因为接口和委托都不能有构造函数。但是,在拒绝没有公共无参数构造函数的类方面,这确实存在漏报。

唯一的另一种方式是在运行时:

if(!typeof(T).IsClass) throw new InvalidOperationException("T must be a class");

同样,where T : struct并不意味着“T必须是值类型”!这意味着“T必须是不可为空的值类型”;涉及Nullable<>的类型不满足T : struct,尽管Nullable<Foo> struct

答案 1 :(得分:7)

public static T GetSerializedCopy<T> (T src) where T : class

This is the link to MSDN for generic type constraints.

答案 2 :(得分:2)

很容易确保......

    public static T GetSerializedCopy<T>(T src) where T : class
    {
        //some code to obtain a copy
        return default(T);
    }

答案 3 :(得分:2)

您可以在界面上使用Type Constraints。 Type constraint

where T : class

答案 4 :(得分:0)

使用它:

where T: class

是..

public static T GetSerializedCopy<T> (T src)
   where T : class
{
  //some code to obtain a copy
}
相关问题