C# generic的初步接触

 搞了几下有关C#generic的一些东西。有两个问题觉得有点tricky,发文记录一下。

1. 声明interface Constraint时后,当constraint的interface也是generic时比较难搞。如:

class MyGeneric<T> where T : MyInterface<T> ?

在这里T是要继承MyInterface<T>的,但这个T明显和MyInterface<T>的T不一样,因此需要写成:

class MyGeneric<T,E> where T : MyInterface<E>

这样,在declare MyGeneric的对象时就要把两个参数都添上,这样做虽然也没什么不妥,但是总给人说不出的别扭的感觉,现在没深入使用到C#,还没有遇到什么问题,但总感觉以后也许会在使用的灵活性上受到局限。

example code:

interface MyInterface<T>
 {
    T GetT();
     void SetT(T val);
 }

 class De<T> : MyInterface<T>
 {
  T data;
  public De()            // place parameterless constructor here in order to use it as parameter in the generic type
  {}
  public T GetT(){return data;}
  public void SetT(T val){data=val;}
 }

 class MyGeneric<T,E> where T:MyInterface<E>,new()
 {
  T member;
  public MyGeneric()
  {
   member = new T();
  }
  
  public void PrintMember()
  {
   System.Console.WriteLine(member.GetT().ToString());
  }

 }
 
    class Program
    {
        static void Main(string[] args)
        {
   MyInterface<int> a = new De<int>();
   MyInterface<float> c = new De<float>();

   MyGeneric<De<int>,int> b = new MyGeneric<De<int>,int>();    //two parameter type(int int) should be the same
   b.PrintMember();
        }
    }

2. 有关int,float等类型没有继承统一的算术运算接口,由此导致类型参数不能使用+,—,×等运算。

这个问题在http://www.osnews.com/story.php/7930/The-Problem-with-.NET-Generics/page1/有详细描述,

最好解决方法为——期待dotnet framework以后的版本能够把所有的int等类型都继承至IArithmetic接口。。。

比较晕的一个solution,呵呵。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值