[英]How to restrict parameter types in generic methods
Say I have 3 classes: A
, B
and C
. 假设我有3个班级:
A
, B
和C
Each of these class have a GetValue()
method, which returns an int
. 这些类每个都有一个
GetValue()
方法,该方法返回一个int
。 I want to create this method: 我想创建这个方法:
int GetTotalValue<T,R>(T c1, R c2)
{
return c1.GetValue() + c2.GetValue()
}
Obviously, this won't work. 显然,这是行不通的。 As not all parameter types have a
GetValue()
method. 由于并非所有参数类型都具有
GetValue()
方法。 So how do I restrict the parameter types T
and R
, so they have to have a GetValue()
method (that returns an int
) 因此,如何限制参数类型
T
和R
,所以它们必须具有GetValue()
方法(返回一个int
)
Have all three implement an interface that contains the GetValue
method and constrain the method to using just those types. 让这三个方法都实现一个包含
GetValue
方法的接口,并将该方法限制为仅使用这些类型。
public interface IGetValue
{
int GetValue();
}
public class A : IGetValue // Same for B and C
{
...
}
Then finally: 然后最后:
int GetTotalValue<T,R>(T c1, R c2) where T : IGetValue, R : IGetValue
{
return c1.GetValue() + c2.GetValue();
}
UPDATE UPDATE
As Alex points out in him comment, this method doesn't need to be generic though, it can be rewritten: 正如Alex在他的评论中指出的那样,该方法虽然不需要通用,但可以重写:
int GetTotalValue(IGetValue c1, IGetValue c2)
{
return c1.GetValue() + c2.GetValue();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.