6
我試圖解決CA2225,其中警告下面ContrainedValue<T>
,用下面的消息來解決CA2225(OperatorOverloadsHaveNamedAlternates):Provide a method named 'ToXXX' or 'FromXXX' as an alternate for operator 'ConstrainedValue<T>.implicit operator T(ConstrainedValue<T>)'.
如何使用時,通用類
我也貼PositiveInteger
來說明用例爲ConstrainedValue<T>
。 ConstrainedValue<T>
使衍生物能夠在構造函數中簡單地指定應用於值類型的約束。這似乎是一個相當乾淨的方式來編碼。鑑於我正在處理泛型類型,有什麼辦法可以解決CA2225警告嗎?我怎樣才能提供替代運營商?
- 也許我可以實現
ToInt
,ToDouble
,等所有的值類型,並讓他們扔如果from
是同類型的呢?但是我認爲ToXXX方法拋出是一個不好的習慣嗎? - 我可以在
ConstrainedValue<T>
和PositiveInteger<T>
之間創建一個層,ConstrainedInteger
類。我可以把ToInt()
放在那個班上。但是爲了滿足CA2225而創建一個圖層似乎是錯誤的,我不認爲警告會在ConstrainedValue<T>
上消失,我不得不壓制這個警告。
代碼:
namespace OBeautifulCode.AutoFakeItEasy
{
using System.Diagnostics;
using Conditions;
/// <summary>
/// Represents a constrained value.
/// </summary>
/// <typeparam name="T">The type of the constrained value.</typeparam>
[DebuggerDisplay("{Value}")]
public abstract class ConstrainedValue<T>
where T : struct
{
/// <summary>
/// Initializes a new instance of the <see cref="ConstrainedValue{T}"/> class.
/// </summary>
/// <param name="value">The value of the <see cref="ConstrainedValue{T}"/> instance.</param>
protected ConstrainedValue(T value)
{
this.Value = value;
}
/// <summary>
/// Gets the underlying value of the instance.
/// </summary>
public T Value { get; }
/// <summary>
/// Performs an implicit conversion from <see cref="ConstrainedValue{T}"/> to the underlying value type.
/// </summary>
/// <param name="from">The <see cref="ConstrainedValue{T}"/> to convert from.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T(ConstrainedValue<T> from)
{
return from.Value;
}
}
/// <summary>
/// Represents a positive integer.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class PositiveInteger : ConstrainedValue<int>
{
/// <summary>
/// Initializes a new instance of the <see cref="PositiveInteger"/> class.
/// </summary>
/// <param name="value">The value held by the <see cref="PositiveInteger"/> instance.</param>
public PositiveInteger(int value)
: base(value)
{
Condition.Requires(value, nameof(value)).IsGreaterThan(0);
}
}
}
奇怪......我實際上試過這個,警告依然存在,但重新開始VS和重建修復它!無論如何,我認爲抑制警告肯定比ToT()更好,這可能會讓最終用戶感到困惑。感謝你的回答!將保持對其他想法的問題。我想提供像ToInt,ToDouble等可讀的替代操作符,因爲它看起來是一種很好的做法,但不知道實現它的最佳方式是什麼。也許這並不重要。 – SFun28
我想我可以實現'ToT()',創建一個從'ConstrainedValue'派生出來的'ConstrainedInteger'並實現一個'ToInt',它簡單地調用'ToT()'然後讓'PositiveInteger'派生出'ConstrainedInteger' – SFun28
,回答的方法並沒有完全奏效。它產生CA1000 - 不要在泛型類型上聲明靜態成員。大聲笑! – SFun28