实现int long等的接口 [英] Implementing interfaces for int long etc.

查看:46
本文介绍了实现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 of System.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 an IComparable of itself (int is an IComparable<int>) and that type T should also be an IGetBytes of <T>.
Int32 on MSDN[^] shows that the int structure is no IGetBytes<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 use MyWrapperClass<T> because the implementation of IComparable and IGetBytes probably won''t be generic for all types... Rather just create a MyIntWrapper Class.


这篇关于实现int long等的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆