C#:限制方法参数中的类型(不是泛型参数)

C#: Restricting Types in method parameters (not generic parameters)(C#:限制方法参数中的类型(不是泛型参数))
本文介绍了C#:限制方法参数中的类型(不是泛型参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写如下函数

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

换句话说,参数类型是 System.Type,我想将允许的 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?

推荐答案

如果您的方法必须将 Type 类型作为参数,则没有办法做到这一点.如果您对方法调用有灵活性,您可以这样做:

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)

并通过调用.GetType()获取Type.

扩大一点.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#:限制方法参数中的类型(不是泛型参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)