我构建了包装类,旨在防止引用类型为 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/