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

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

问题描述

阅读this,我了解到可以通过使方法成为泛型来允许方法接受多种类型的参数方法.在示例中,以下代码与类型约束一起使用以确保U"是 IEnumerable.

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();
}

我发现了更多允许添加多个类型约束的代码,例如:

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
}

但是,此代码似乎强制arg 必须同时是ParentClass ChildClass 的类型.我想要做的是说 arg 可以是 ParentClass 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
}

一如既往地感谢您的帮助!

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);

如果这些是泛型类的一部分,它们将优先于方法的泛型版本.

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

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

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