开发者

Automatic conversion of wrapper in C#

I've build wrapper-class intended to prevent reference types of being null, as a pre-condition code contra开发者_开发知识库ct.

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;
    }

}

This works finely, but a cast is always needed like when dealing with Nullable:

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

Would it be possible to have the parameter of type NonNullable behave as if it were of type T, without having to cast it? Like in Spec#:

public string Foo(Bar! bar)


You could avoid the casting by making the object itself accessible via a Value property, but it's debatable whether that's any better than casting it:

Console.WriteLine(bar.Value);

There are even tricks you can use to tell tools like ReSharper that this value is not null, either via XML or in-code annotations:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜