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

后端 未结 6 684
太阳男子
太阳男子 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:56

    If your method has to take a Type type as it's argument, there's no way to do this. If you have flexibility with the method call you could do:

    public void Foo(MyClass myClass)
    

    and the get the Type by calling .GetType().

    To expand a little. System.Type is the type of the argument, so there's no way to further specify what should be passed. Just as a method that takes an integer between 1 and 10, must take an int and then do runtime checking that the limits were properly adhered to.

提交回复
热议问题