SFu*_*n28 6 .net c# generics code-analysis implicit-conversion
我正在尝试使用以下消息解决CA2225(ContrainedValue<T>
下面的WARN):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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过实际执行它所说的操作来使代码分析变得愉快:
将其插入ConstrainedValue<T>
,警告就会消失。
public T ToT()
{
return this.Value;
}
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我宁愿抑制该消息,即使该语言不提供强制转换,您也已经提供了一种获取值的方法。