使用通用 class 时如何修复 CA2225 (OperatorOverloadsHaveNamedAlternates)

How to fix CA2225 (OperatorOverloadsHaveNamedAlternates) when using generic class

我正在尝试解决下面 ContrainedValue<T> 上的警告 CA2225,并显示以下消息: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 警告?我如何提供替代运营商?

代码:

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

您可以通过实际执行它所说的来使代码分析变得愉快:

将此插入 ConstrainedValue<T>,警告将消失。

public T ToT()
{
  return this.Value;
}

就我个人而言,我宁愿抑制消息,你已经提供了一种获取值的方法,即使该语言不提供转换。