簡體   English   中英

無法在C#的通用約束中使用結構類型

[英]Not able to use struct type in Generic constraint in C#

發現問題時,我正在使用通用約束。 除了在編譯時顯示的錯誤提示,我無法找到答案。

struct MyStruct
{
    public void Get()
    {

    }
}

class MyClass
{
    public void Get()
    {

    }
}


public class Stable<T> where T : MyStruct // NOT Allowed
{

}

public class Stable<T> where T : MyClass //Allowed
{

}

public class Stable<T> where T : struct //Allowed
{

}

public class Stable<T> where T : class //Allowed
{

}

默認情況下,結構是密封的,因此您不應在此處使用泛型。

采用:

public class StableStruct : Stable<MyStruct>
{
}

一個struct不能從另一個struct繼承。 因此,在您的示例(不是工作示例)中, T始終必須是MyStruct ,這使得在這里泛型的使用非常無用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM