一切都为空的C#泛型类型约束 [英] C# generic type constraint for everything nullable

查看:269
本文介绍了一切都为空的C#泛型类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个班:

  public class Foo< T> T:? 
{
私人T项;

public bool IsNull()
{
return item == null;
}

}

现在我正在寻找一种类型约束条件,它允许我将所有的东西用作类型参数,可以是 null 。这意味着所有引用类型以及所有 Nullable T?)类型:

  Foo< String> ... = ... 
Foo< int?> ... = ...

应该是可以的。

使用 class 作为类型约束只允许我使用引用类型。



附加信息:
我正在编写一个管道和过滤器应用程序,并希望使用 null 引用作为传入管道的最后一项,所以每个过滤器都可以很好地关闭,清理等等。 解决方案

如果你愿意做一个运行时检查Foo的构造函数而不是编译时检查,你可以检查这个类型是不是一个引用或可为空的类型,如果是这样的话就抛出一个异常。



我意识到只有运行时检查可能是不可接受的,但以防万一:

  public class Foo< T> 
{
私人T项;

public Foo()
{
var type = typeof(T);

if(Nullable.GetUnderlyingType(type)!= null)
return;

if(type.IsClass)
return;

抛出新的InvalidOperationException(类型不可为空或引用类型。);
}

public bool IsNull()
{
return item == null;


$ / code>

然后下面的代码编译,但最后一个 foo3 )会在构造函数中抛出一个异常:

  var foo1 = new FOO<诠释>(); 
Console.WriteLine(foo1.IsNull());

var foo2 = new Foo< string>();
Console.WriteLine(foo2.IsNull());

var foo3 = new Foo< int>(); // thrrow
Console.WriteLine(foo3.IsNull());


So I have this class:

public class Foo<T> where T : ???
{
    private T item;

    public bool IsNull()
    {
        return item == null;
    }

}

Now I am looking for a type constraint that allows me to use everything as type parameter that can be null. That means all reference types, as well as all the Nullable (T?) types:

Foo<String> ... = ...
Foo<int?> ... = ...

should be possible.

Using class as the type constraint only allows me to use the reference types.

Additional Information: I am writing a pipes and filters application, and want to use a null reference as the last item that passes into the pipeline, so that every filter can shut down nicely, do cleanup, etc...

解决方案

If you are willing to make a runtime check in Foo's constructor rather than having a compile-time check, you can check if the type is not a reference or nullable type, and throw an exception if that's the case.

I realise that only having a runtime check may be unacceptable, but just in case:

public class Foo<T>
{
    private T item;

    public Foo()
    {
        var type = typeof(T);

        if (Nullable.GetUnderlyingType(type) != null)
            return;

        if (type.IsClass)
            return;

        throw new InvalidOperationException("Type is not nullable or reference type.");
    }

    public bool IsNull()
    {
        return item == null;
    }
}

Then the following code compiles, but the last one (foo3) throws an exception in the constructor:

var foo1 = new Foo<int?>();
Console.WriteLine(foo1.IsNull());

var foo2 = new Foo<string>();
Console.WriteLine(foo2.IsNull());

var foo3= new Foo<int>();  // THROWS
Console.WriteLine(foo3.IsNull());

这篇关于一切都为空的C#泛型类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆