c# - 如何定义通用约束以便我可以使用 ??合并运算符

标签 c# generics

我正在尝试定义一个泛型类

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/

相关文章:

c# - WPF,ScrollViewer 在长按之前消耗触摸

c# - 比较这两个列表的最有效方法是什么?

c# - 仅在持久函数中扇出(并忘记)

java - 自定义泛型解释

swift - 无法推断通用参数 T

c# - 编辑 XAML 导致 Visual Studio 的设计器崩溃

c# - 使用反射在签名为 : SomeObject. 的对象实例上调用泛型方法 SomeGenericInstanceMethod<T>(T argument)

java - 在Java中使用泛型,有人可以解释一下我做错了什么吗

Java 泛型和数组类型

c# - mysqldump.exe 没有对 mysql 数据库进行完整备份