![](/img/trans.png)
[英]Cannot implicitly cast to IEnumerable<T>… but I can the other way… why?
[英]Cannot implicitly cast IEnumerable
我有一個類,它指示對方法的調用是成功(帶有值)還是有錯誤。
internal sealed class ValueOrError<TValue>
{
public bool IsError => _error is not null;
public bool IsSuccess => !IsError;
private TValue? _value;
private Error? _error;
private ValueOrError() { }
public TValue? Value =>
_error is null
? _value
: throw new InvalidOperationException("Is an error type");
public Error Error => _error ?? throw new InvalidOperationException("Not an error type");
public static ValueOrError<TValue> FromValue(TValue? result) =>
new ValueOrError<TValue> { _value = result };
public static ValueOrError<TValue> FromError(Error error) =>
new ValueOrError<TValue> { _error = error ?? throw new ArgumentNullException(nameof(error)) };
public static implicit operator ValueOrError<TValue>(TValue value) => ValueOrError<TValue>.FromValue(value);
public static implicit operator ValueOrError<TValue>(Error error) => ValueOrError<TValue>.FromError(error);
}
除非TValue
是IEnumerable<T>
,否則我可以隱式轉換。
// Works
ValueOrError<int> x = 1;
// Fails
ValueOrError<IEnumerable<int>> y = Enumerable.Empty<int>();
無法將類型“System.Collections.Generic.IEnumerable”隱式轉換為“AppLayer.ValueOrError”
但是,我可以創建“長路”類型的結果
c# // Works ValueOrError<IEnumerable<int>>.FromValue(Enumerable.Empty<int>());
如果它有用, Error
的來源是
public class Error
{
public string Message { get; }
[JsonConstructor]
public Error(string message)
{
Message = message ?? throw new ArgumentNullException(nameof(message));
}
}
如果您查看有關用戶定義轉換的 C# 規范:
使用隱式或顯式運算符的先決條件之一是
S₀ 和 T₀ 都不是 interface_type。
因此,如果您真的想使用隱式轉換,則必須將接口引用轉換為類引用(例如通過調用.ToArray()
)。
或者您可以創建一個靜態類來利用類型推斷:
internal static class ValueOnError
{
public static ValueOnError<TValue> FromValue<TValue>(TValue value)
=> ValueOnError<TValue>.FromValue(value);
}
然后你可以寫
var y = ValueOnError.FromValue(Enumerable.Empty<int>());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.