C# 默认(T)返回null,其中T从DataContext继承

C# 默认(T)返回null,其中T从DataContext继承,c#,.net,generics,C#,.net,Generics,我的示例代码: public class GenericClass<T> : IDisposable where T: System.Data.Linq.DataContext { public T context{ get; private set; } public GenericClass() { this.context= default(T); // default(T) return null //

我的示例代码:

public class GenericClass<T> : IDisposable where T: System.Data.Linq.DataContext 
{
    public T context{ get; private set; }       

    public GenericClass()
    {
        this.context= default(T); // default(T) return null
        // code
    }       

    public void Dispose()
    {
        context.Dispose();
    }
}
using (GenericClasss <DataAccessDataContext> dataAccess = new GenericClasss <DataAccessDataContext>())
{
  //code
}
public类GenericClass:IDisposable其中T:System.Data.Linq.DataContext
{
公共T上下文{get;私有集;}
公共泛型类()
{
this.context=default(T);//default(T)返回null
//代码
}       
公共空间处置()
{
context.Dispose();
}
}
使用GenericClasss示例代码:

public class GenericClass<T> : IDisposable where T: System.Data.Linq.DataContext 
{
    public T context{ get; private set; }       

    public GenericClass()
    {
        this.context= default(T); // default(T) return null
        // code
    }       

    public void Dispose()
    {
        context.Dispose();
    }
}
using (GenericClasss <DataAccessDataContext> dataAccess = new GenericClasss <DataAccessDataContext>())
{
  //code
}
使用(GenericClasss dataAccess=new GenericClasss())
{
//代码
}
其中,
DataAccessDataContext
是一个.dbml(继承System.Data.Linq.DataContext)并具有默认构造函数


对不起,如果事情很简单,我没有注意到。非常感谢。

这是引用类型的默认值的预期行为,即
default(T)
,其中
T
是引用类型,如果
null
尝试实例化新上下文,则可以执行以下操作:

public GenericClass()
{
    this.context = new T();
}  

如果无法从泛型类型创建新对象,则应使用
new()
关键字:

public class GenericClass<T> : IDisposable where T: System.Data.Linq.DataContext, new()

编译器必须知道
T
具有默认构造函数。

使用泛型
new()
约束定义类:

public class GenericClass<T> : IDisposable where T: System.Data.Linq.DataContext, new()
{
    ...

请参见

您期望的是什么?这就是默认值应该做的。你期望或试图实现什么?你的问题/问题是什么?对不起,混淆了,我需要新的T@Nacho混淆可能是您没有约束泛型类型。如果需要,可以添加
new()
约束,强制泛型具有空构造函数
where T:System.Data.Linq.DataContext,new()
很抱歉我的困惑,非常感谢much@Nacho欢迎你,伙计!这根本不是问题。这正是我需要的,非常感谢。如果需要调用非默认构造函数(例如带有连接字符串参数的构造函数),可以使用Activator.CreateInstance,因为new()泛型约束仅适用于默认的无参数构造函数。是,如果您需要更好的性能,也可以使用另一种方法:非常好,谢谢!