C#: Restricting Types in method parameters (not generic parameters)

后端 未结 6 672
太阳男子
太阳男子 2020-12-11 03:21

I\'d like to code a function like the following

public void Foo(System.Type t where t : MyClass)
{ ... }

In other words, the argument type

6条回答
  •  醉梦人生
    2020-12-11 03:51

    Specifying the type be MyClass, or derived from it, is a value check on the argument itself. It's like saying the hello parameter in

    void Foo(int hello) {...}
    

    must be between 10 and 100. It's not possible to check at compile time.

    You must use generics or check the type at run time, just like any other parameter value check.

提交回复
热议问题