如何限制泛型方法中的参数类型
How to restrict parameter types in generic methods
假设我有 3 个 class:A
、B
和 C
。其中每个 class 都有一个 GetValue()
方法,其中 returns 一个 int
。我想创建这个方法:
int GetTotalValue<T,R>(T c1, R c2)
{
return c1.GetValue() + c2.GetValue()
}
显然,这行不通。因为并非所有参数类型都有 GetValue()
方法。那么我如何限制参数类型T
和R
,所以他们必须有一个GetValue()
方法(即returns和int
)
让这三个都实现一个包含 GetValue
方法的接口,并将该方法限制为仅使用这些类型。
public interface IGetValue
{
int GetValue();
}
public class A : IGetValue // Same for B and C
{
...
}
然后最后:
int GetTotalValue<T,R>(T c1, R c2) where T : IGetValue, R : IGetValue
{
return c1.GetValue() + c2.GetValue();
}
更新
正如 Alex 在他的评论中指出的那样,此方法不需要通用,但可以重写:
int GetTotalValue(IGetValue c1, IGetValue c2)
{
return c1.GetValue() + c2.GetValue();
}
假设我有 3 个 class:A
、B
和 C
。其中每个 class 都有一个 GetValue()
方法,其中 returns 一个 int
。我想创建这个方法:
int GetTotalValue<T,R>(T c1, R c2)
{
return c1.GetValue() + c2.GetValue()
}
显然,这行不通。因为并非所有参数类型都有 GetValue()
方法。那么我如何限制参数类型T
和R
,所以他们必须有一个GetValue()
方法(即returns和int
)
让这三个都实现一个包含 GetValue
方法的接口,并将该方法限制为仅使用这些类型。
public interface IGetValue
{
int GetValue();
}
public class A : IGetValue // Same for B and C
{
...
}
然后最后:
int GetTotalValue<T,R>(T c1, R c2) where T : IGetValue, R : IGetValue
{
return c1.GetValue() + c2.GetValue();
}
更新
正如 Alex 在他的评论中指出的那样,此方法不需要通用,但可以重写:
int GetTotalValue(IGetValue c1, IGetValue c2)
{
return c1.GetValue() + c2.GetValue();
}