c# - C#中wrapper的自动转换

标签 c# wrapper non-nullable preconditions

我构建了包装类,旨在防止引用类型为 null,作为前提条件代码契约。

public sealed class NotNullable<T> 
    where T : class
{
    private T t;

    public static implicit operator NotNullable<T>(T otherT)
    {
        otherT.CheckNull("Non-Nullable type");
        return new NotNullable<T> {t = otherT};
    }

    public static implicit operator T(NotNullable<T> other)
    {
        return other.t;
    }

}

这很好用,但是像处理 Nullable 一样总是需要强制转换:

public void Foo(NonNullable<Bar> bar)
{
    Console.WriteLine((Bar)bar);
}

是否可以让 NonNullable 类型的参数表现得像 T 类型的参数,而无需强制转换它? 就像在 Spec# 中一样:

public string Foo(Bar! bar)

最佳答案

您可以通过 Value 属性使对象本身可访问来避免强制转换,但这是否比强制转换更好是值得商榷的:

Console.WriteLine(bar.Value);

您甚至可以使用一些技巧来告诉 ReSharper 这样的工具该值不为空,无论是通过 XML 还是代码内注释:

[NotNull]
public T Value { get { return t; } }

关于c# - C#中wrapper的自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7704715/

相关文章:

c# - 如何在静态方法中访问下拉列表

c# - 如何将 "type here"消息添加到 WPF 文本框?

.net - 在 .NET 中使用 C++/CLI 实用程序 :

c# - 我怎样才能避免到处创建新的包装器对象?

c# - 是否有任何 librtmp c# .net 包装器?

java - Eclipse 空分析 : The expression of type int needs unchecked conversion to conform to '@Nonnull Integer'

objective-c - 默认情况下,Objective-C 函数结果是否为非空?

c# - 在 ASP.NET 页面中查找客户端位置

C# 将科学计数法中的数字从 E+### 减少到 E+##

c# - 使不可空值类型可空