C#:在方法参数(不是通用的参数)限制类型 [英] C#: Restricting Types in method parameters (not generic parameters)

查看:817
本文介绍了C#:在方法参数(不是通用的参数)限制类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想$,如C $ CA功能如下

I'd like to code a function like the following

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

在换句话说,参数类型为的System.Type ,我想限制所允许的键入取值那些从获得 MyClass的

In other words, the argument type is System.Type, and I want to restrict the allowed Types to those that derive from MyClass.

有没有什么办法语法指定这个,或者做 T 已在运行时检查?

Is there any way to specify this syntactically, or does t have to be checked at runtime?

推荐答案

如果你的方法必须采取的类型的类型,因为它的说法,我不认为有办法做到这一点。如果你有方法灵活调用,你可以做:公共无效美孚(MyClass的MyClass的)和获得型致电.GetType()

If your method has to take a Type type as it's argument, I don't think there's a 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().

要扩大一点。 System.Type的是参数的类型,所以没有办法进一步明确哪些应该传递。就像一个方法,需要1到10之间的整数,必须采取一个int,然后进行运行时检查的范围是适当的遵守。

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.

这篇关于C#:在方法参数(不是通用的参数)限制类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆