泛型方法多(OR)类型约束 [英] Generic method multiple(OR) type constraint

查看:250
本文介绍了泛型方法多(OR)类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时,我了解到,有可能允许一个方法通过使一个通用接受多个类型的参数方法。在这个例子中,下面的code与类型约束用于确保U是的IEnumerable< T>

Reading this, I learned it was possible to allow a method to accept parameters of multiple types by making it a generic method. In the example, the following code is used with a type constraint to ensure "U" is an IEnumerable<T>.

public T DoSomething<U, T>(U arg) where U : IEnumerable<T>
{
    return arg.First();
}

我发现了一些更code这使得添加多个类型的限制,如:

I found some more code which allowed adding multiple type constraints, such as:

public void test<T>(string a, T arg) where T: ParentClass, ChildClass 
{
    //do something
}

不过,这code似乎强制执行 ARG 必须是一个类型父类的<强>和 ChildClass 。我想要做的是说,ARG可能是一个类型的父类 ChildClass 以下面的方式:

However, this code appears to enforce that arg must be both a type of ParentClass and ChildClass. What I want to do is say that arg could be a type of ParentClass or ChildClass in the following manner:

public void test<T>(string a, T arg) where T: string OR Exception
{
//do something
}

您的帮助是AP preciated一如既往!

Your help is appreciated as always!

推荐答案

这是不可能的。你可以,但是,重载定义为特定类型的:

That is not possible. You can, however, define overloads for specific types:

public void test(string a, string arg);
public void test(string a, Exception arg);

如果这些都是一个泛型类的一部分,他们将pferred在方法的通用版本$ P $。

If those are part of a generic class, they will be preferred over the generic version of the method.

这篇关于泛型方法多(OR)类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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