如何限制泛型函数只接受某些类型的类 [英] How to restrict generic function to accept only some type of classes
问题描述
我正在尝试执行以下操作:
I'm trying to do the following:
public class A
{
}
public class B
{
}
在项目的某个地方我想要这个:
Somewhere along the project I want to have this:
public class C
{
public T func<T>(T obj) [where T can be either of class A or class B]
{
obj.x = 100;
return obj;
}
}
我一直在尝试:
public T func<T>(T obj) where T: A, B
但这给了我
类型类约束'B'必须位于其他任何约束之前.
The type class constraint 'B' must come before any other constraint.
有人可以解释我如何使 func
仅接受A类或B类吗?
Can someone explain me how to make func
accept only class A or class B?
推荐答案
正如问题中所描述的那样,此工作最好由超载分辨率处理:
Exactly as it's described in the question, this job is better handled by overload resolution:
public class C
{
public A func(A obj)
{
obj.x = 100;
return obj;
}
public B func(B obj)
{
obj.x = 100;
return obj;
}
}
但是我知道A和B可能是任意数量的类型的占位符,并且将它们全部考虑在内可能会很乏味.在这种情况下,您需要每个类都支持的通用接口:
But I understand that A and B may be placeholders for any number of types, and it could get tedious to account for them all. In that case, you'll need a common interface that's supported by each of your classes:
interface IBase
{
int x;
}
public class C
{
public IBase func(IBase obj)
{
obj.x = 100;
return obj;
}
}
请注意,此时我们仍然不需要泛型.此外,您可能需要支持在通用界面下无法完全融合在一起的多种类型.在这种情况下,仍会构建接口,并在该接口中放置尽可能多的类型.如果需要,可以为更多类型创建另一个接口...依此类推...然后在接口和特定类型之间可以使用重载解析来处理事情.
Note that at this point we still have no need of generics. Additionally, you may need to support a number of types that won't all fit together under a common interface. In this case, still build the interface and put as many types with that interface as possible. If needed, build another interface for a few more types ... and so on... and then between interfaces and specific types you can handle things with overload resolution.
这篇关于如何限制泛型函数只接受某些类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!