搞了几下有关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,呵呵。