相关疑难解决方法(0)

在泛型方法中检查null的非类约束类型参数的实例

我目前有一个通用的方法,我想在它们之前对参数进行一些验证.具体来说,如果type参数的实例T是引用类型,我想检查它是否是null,ArgumentNullException如果它为null则抛出它.

有点像:

// This can be a method on a generic class, it does not matter.
public void DoSomething<T>(T instance)
{
    if (instance == null) throw new ArgumentNullException("instance");
Run Code Online (Sandbox Code Playgroud)

请注意,我不希望使用来约束我喜欢的类型参数class的约束.

我以为我可以用马克Gravell的答案"我怎么比一般类型为默认值?" ,并像这样使用EqualityComparer<T>:

static void DoSomething<T>(T instance)
{
    if (EqualityComparer<T>.Default.Equals(instance, null))
        throw new ArgumentNullException("instance");
Run Code Online (Sandbox Code Playgroud)

但它在调用时给出了一个非常模糊的错误Equals:

无法使用实例引用访问成员'object.Equals(object,object)'; 用类型名称来限定它

如何在不限制为值或引用类型的情况下检查T反对的实例?nullT

.net c# null iequalitycomparer equals-operator

0
推荐指数
1
解决办法
1640
查看次数

标签 统计

.net ×1

c# ×1

equals-operator ×1

iequalitycomparer ×1

null ×1