编译器错误 CS0313
更新:2007 年 11 月
错误消息
不能将类型“type1”用作泛型类型或方法“type2”中的类型参数“parameter name”。可为 null 的类型“type1”未满足“type2”的约束。可为 null 的类型无法满足任何接口约束。
可为 null 的类型与其不可为 null 的对应项不是等效的。在下面的示例中,ImplStruct 满足 BaseInterface 约束,但 ImplStruct? 不满足该约束,因为 Nullable<ImplStruct> 未实现 BaseInterface。
更正此错误
使用下面的代码作为示例时,一种解决方案是将常规 ImplStruct 指定为对 TestMethod 的调用中的第一个类型参数。然后,修改 TestMethod,在其返回语句中创建 Implstruct 的可为 null 的版本:
return new Nullable<T>(t);
示例
下面的代码生成 CS0313:
// cs0313.cs
public interface BaseInterface { }
public struct ImplStruct : BaseInterface { }
public class TestClass
{
public T? TestMethod<T, U>(T t) where T : struct, U
{
return t;
}
}
public class NullableTest
{
public static void Run()
{
TestClass tc = new TestClass();
tc.TestMethod<ImplStruct?, BaseInterface>(new ImplStruct?()); // CS0313
}
public static void Main()
{ }
}