实现int long等的接口 [英] Implementing interfaces for int long etc.
本文介绍了实现int long等的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下内容:
Say I have the following :
public class SomeClass<T> : where T : ICompareable<T> , IGetBytes<T>
{...
现在,当我使用以下命令时:
Now when I use the following :
var s = new SomeClass<int>();
我收到一条错误消息:
I get an error that :
The type 'int' cannot be used as type parameter 'T' in the generic type or method 'SomeClass<T>'. There is no boxing conversion from 'int' to 'IGetBytes<int>'.
如何为int
等实现IGetBytes
.
How can I implement the IGetBytes
for an int
etc.
推荐答案
您不能在
int
中实现接口,因为System.Int32
的代码不是你的.但是您可以创建一个实现以下接口的包装器类:
You cannot implement interfaces in
int
because the code ofSystem.Int32
isn''t yours. But you can create a wrapper class that implements the interfaces as the following:
public class MyWrapperClass<T> : ICompareable<T>, IGetBytes<T>
{
public MyWrapperClass(T arg)
{
// ...
}
// ...
}
并将您的类与包装一起使用:
and use your class with the wrapper:
public class SomeClass<T>
{
void MyMethod(T arg)
{
MyWrapperClass<T> wrappedArg = new MyWrapperClass<T>(arg);
// ...
}
}
您要说的是T的类型应为自身的IComparable
(int
为IComparable<int>
),并且T的类型也应为是< T>的IGetBytes
.
MSDN上的Int32 [
What you are saying is that the type of T should be anIComparable
of itself (int
is anIComparable<int>
) and that type T should also be anIGetBytes
of <T>.
Int32 on MSDN[^] shows that theint
structure is noIGetBytes<int>
so it can not be used as type T here.
Look at Shmuel Zangs answer for a workaround. Although I am not sure you should useMyWrapperClass<T>
because the implementation ofIComparable
andIGetBytes
probably won''t be generic for all types... Rather just create aMyIntWrapper Class
.
这篇关于实现int long等的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文