C# 扩展模糊错误
我有下节课:C# 扩展模糊错误,c#,C#,我有下节课: public static class Monads { public static TResult With<TInput, TResult> (this TInput o, Func<TInput, TResult> evaluator) where TInput: class where TResult: class { if (o == null) return null
public static class Monads
{
public static TResult With<TInput, TResult>
(this TInput o, Func<TInput, TResult> evaluator)
where TInput: class
where TResult: class
{
if (o == null) return null;
return evaluator(o);
}
public static Nullable<TResult> With<TInput, TResult>
(this TInput o, Func<TInput, TResult> evaluator)
where TInput : class
where TResult : struct
{
if (o == null) return null;
return evaluator(o);
}
}
公共静态类monad
{
带有
(此TInput o,函数计算器)
地点:班级
结果:在哪里上课
{
如果(o==null)返回null;
返回评估器(o);
}
可为空的公共静态
(此TInput o,函数计算器)
地点:班级
其中TResult:struct
{
如果(o==null)返回null;
返回评估器(o);
}
}
当我尝试使用它时,出现了一个错误:
“错误以下方法或属性之间的调用不明确:'CoreLib.Monads.With(TInput,System.Func)
和'CoreLib.Monads.With(TInput,System.Func)
”
但这种方法根据类型的约束而有所不同,并且可以为null的是struct。
但是,此代码可以正常工作:
public static class Monads
{
public static TResult Return<TInput, TResult>
(this TInput o, Func<TInput, TResult> evaluator,
TResult failureValue)
where TInput: class
{
if (o == null) return failureValue;
return evaluator(o);
}
public static TResult Return<TInput, TResult>
(this Nullable<TInput> o, Func<TInput, TResult> evaluator,
TResult failureValue)
where TInput : struct
{
if (!o.HasValue) return failureValue;
return evaluator(o.Value);
}
}
公共静态类monad
{
公共静态TResult返回
(此TInput o,函数计算器,
t结果失败值)
地点:班级
{
如果(o==null)返回failureValue;
返回评估器(o);
}
公共静态TResult返回
(此函数可为空,函数求值器,
t结果失败值)
其中TInput:struct
{
如果(!o.HasValue)返回failureValue;
返回评估器(o.Value);
}
}
此错误的原因是什么?在第一个代码中,您具有相同的参数类型(此TInput o,Func计算器) 要重载方法,参数必须是不同的类型,否则必须有不同数量的参数。在您的示例中:
public static TResult With<TInput, TResult>
(this TInput o, Func<TInput, TResult> evaluator)
public static Nullable<TResult> With<TInput, TResult>
(this TInput o, Func<TInput, TResult> evaluator)
publicstatictresult与
(此TInput o,函数计算器)
可为空的公共静态
(此TInput o,函数计算器)
您可以看到这些参数完全相同。您的第二个示例之所以有效,是因为您正在为两种不同类型的对象编写扩展方法,this Nullable o
和this TInput o