How to restrict T to value types using a constraint?

后端 未结 6 1816
情歌与酒
情歌与酒 2020-12-16 11:46

I want to restrict the possible types N can take-on using a constraint. I wish to restrict N to be either a int or a decimal.

public static Chart PopulateIn         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 12:12

    To answer the question in the Title but not the body of the question.

    To cover all types commonly meant by Value Types (which includes Nullable Value Types, and also string even though it's technically a Reference type), you need 3 overloads:

    public void Foo(T arg) where T : struct
    public void Foo(T? arg) where T : struct
    public void Foo(string arg)
    

    From the MSDN Docs on generic constraints:

    where T : struct The type argument must be a non-nullable value type.

提交回复
热议问题