[英]Automatic conversion of wrapper in C#
我已經構建了包裝器類,以防止引用類型為空,作為前提條件代碼約定。
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一樣,而不必進行強制轉換? 就像規格#:
public string Foo(Bar! bar)
您可以通過使用Value
屬性使對象本身可訪問來避免強制轉換,但是是否有比強制轉換更好的方法尚待商::
Console.WriteLine(bar.Value);
您甚至可以使用技巧,通過XML或代碼內注釋來告訴諸如ReSharper之類的工具此值不為null:
[NotNull]
public T Value { get { return t; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.