简体   繁体   English

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

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

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 is System.Type , and I want to restrict the allowed Type s to those that derive from MyClass .换句话说,参数类型是System.Type ,我想将允许的Type限制为从MyClass派生的Type

Is there any way to specify this syntactically, or does t have to be checked at runtime?有没有什么办法语法中指明,或不t都在运行时进行检查?

If your method has to take a Type type as it's argument, there's no way to do this.如果您的方法必须采用Type类型作为参数,则无法执行此操作。 If you have flexibility with the method call you could do:如果您对方法调用具有灵活性,则可以执行以下操作:

public void Foo(MyClass myClass)

and the get the Type by calling .GetType() .并通过调用.GetType()获取Type

To expand a little.稍微扩展一下。 System.Type is the type of the argument, so there's no way to further specify what should be passed. System.Type是参数的类型,因此无法进一步指定应传递的内容。 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.就像采用 1 到 10 之间的整数的方法一样,必须采用 int,然后进行运行时检查是否正确遵守了限制。

Specifying the type be MyClass, or derived from it, is a value check on the argument itself.将类型指定为 MyClass 或从它派生,对参数本身的值检查 It's like saying the hello parameter in这就像在说 hello 参数

void Foo(int hello) {...}

must be between 10 and 100. It's not possible to check at compile time.必须在 10 到 100 之间。无法在编译时进行检查。

You must use generics or check the type at run time, just like any other parameter value check.您必须在运行时使用泛型或检查类型,就像任何其他参数值检查一样。

You can use the following:您可以使用以下内容:

public void Foo<T>(T variable) where T : MyClass
{ ... }

The call would be like the following:调用如下所示:

{
    ...
    Foo(someInstanceOfMyClass);
    ...
}

What you want could theoretically be done with attributes.你想要的理论上可以用属性来完成。 But this is much clearer (imo) and does exactly the same thing:但这更清晰(imo)并且做完全相同的事情:

public void Foo(MyClass m) {
   Type t = m.GetType();
   // ...
}

why don't you use你为什么不使用

public void foo<t>();

instead?反而?

You can also use an extension method, which will be available for all objects convertible to MyClass:您还可以使用扩展方法,该方法可用于所有可转换为 MyClass 的对象:

public static class MyClassExtensions
{
    public static void Foo(this MyClass obj)
    {
       // ...
    }
}

And you can use it as if it were an ordinary method of an object:您可以像使用对象的普通方法一样使用它:

var x = new MyClass();
x.Foo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM