泛型方法多重 (OR) 类型约束 [英] Generic method multiple (OR) type constraint
问题描述
阅读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屋!