我正在尝试定义一个泛型类
public abstract class RepositoryBase<TDatabase, TKey, T> : IRepository<TKey, T>
where T : class
where TDatabase : IDatabase
{
private TDatabase db;
private readonly IDbSet<T> dbset;
protected IDatabaseFactory<TDatabase> DatabaseFactory { get; private set; }
protected TDatabase Database
{
get
{
return db ?? (db = DatabaseFactory.Get());
}
}
...
}
在线 return db ?? (db = DatabaseFactory.Get());
,编译器提示“'??' 的左操作数”运算符应该是引用或可空类型"
我理解错误,但不知道如何对 TDatabase 类型参数施加约束,以便编译器知道它是引用类型或可空类型。
如何让编译器满意?
最佳答案
你必须指出TDatabase
是一个引用类型
where TDatabase : class, IDatabase
MSDN, Constraints on Type Parameters (C# Programming Guide)
where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
MSDN, ?? Operator (C# Reference) :
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
关于c# - 如何定义通用约束以便我可以使用 ??合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10014400/