通用方法多重(OR)类型约束 [英] Generic method multiple (OR) type constraint
问题描述
阅读此,我了解到可以通过使方法成为通用方法来允许方法接受多种类型的参数方法.在该示例中,以下代码与类型约束一起使用,以确保"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();
}
我发现了更多允许添加多个类型约束的代码,例如:
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屋!