共用方式為


編譯器錯誤 CS0313

更新:2007 年 11 月

錯誤訊息

型別 'type1' 不能做為泛型型別或方法 'type2' 中的型別參數 'parameter name'。可為 Null 的型別 'type1' 未滿足 'type2' 的條件約束。可為 Null 的型別無法滿足所有介面條件約束。

可為 Null 的型別不等於它的不可為 Null 對等型別。在下列範例中,因為 Nullable<ImplStruct> 未實作 BaseInterface,所以 ImplStruct 滿足 BaseInterface 條件約束 (Constraint),但是 ImplStruct? 則不滿足。

若要更正這個錯誤

  • 如下列程式碼範例所示,其中一種解決方案是將一般 ImplStruct 指定為 TestMethod 呼叫的第一個型別引數。然後修改 TestMethod,在其傳回陳述式中建立可為 Null 版本的 Implstruct:

    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()
    { }
}

請參閱

參考

可為 Null 的型別 (C# 程式設計手冊)