class For<T> //后面还有一些关键字~可以指定T必须是int或者long~关键字我忘记了~还有一种方法~~ class For<T> { void Function() { T i; ((int)i)++; } }
To he_8134: 那个关键字是where吗? 我这样用不行: class For<T> where T : int, byte, long, uint, ulong{}Error: 'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.还有((int)i)++;也不行 Error: Cannot convert type 'T' to 'int'
呵呵。C#的范型是不支持对范型类型的+,++,-,等操作。 甚至这样的约束也没提供。所以是没什么办法的。这一点不同于C++,C++是没有约束的,所以你可以写出调用该 模板类型的任何方法,操作。但也让代码变的复杂,难读。 因为你不知道可能传进来的范型参数是怎么样一个类,还是基本 类型,有什么方法。 public abstract class BaseCalculator<T> { public abstract T Add(T arg1,T arg2); public abstract T Subtract(T arg1,T arg2); public abstract T Divide(T arg1,T arg2); public abstract T Multiply(T arg1,T arg2); } public class MyCalculator : BaseCalculator<int> { public override int Add(int arg1, int arg2) { return arg1 + arg2; } //Rest of the methods } A generic interface will yield a somewhat cleaner solution as well: public interface ICalculator<T> { T Add(T arg1,T arg2); //Rest of the methods } public class MyCalculator : ICalculator<int> { public int Add(int arg1, int arg2) { return arg1 + arg2; } //Rest of the methods }
看来是没办法的了,呵呵,只好 class ForInt class ForLong class ForByte...下去 谢谢
另类方法 class For <T> { void Function() { T i; if(typeof(T)==typeof("System.Int32")){ i=Int32.Parse(i.ToString())+1; }else if(typeof(T)==typeof("System.Long")){ i=Long.Parse(i.ToString())+1; } } }
To haiwangstar: 不是为了泛型而泛型,呵呵 程序里有很多类,它们唯一区别就在类型上,所以想偷个懒。。
class For<T>
{
void Function()
{
T i;
((int)i)++;
}
}
那个关键字是where吗?
我这样用不行:
class For<T> where T : int, byte, long, uint, ulong{}Error:
'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.还有((int)i)++;也不行
Error:
Cannot convert type 'T' to 'int'
甚至这样的约束也没提供。所以是没什么办法的。这一点不同于C++,C++是没有约束的,所以你可以写出调用该
模板类型的任何方法,操作。但也让代码变的复杂,难读。
因为你不知道可能传进来的范型参数是怎么样一个类,还是基本
类型,有什么方法。
public abstract class BaseCalculator<T>
{
public abstract T Add(T arg1,T arg2);
public abstract T Subtract(T arg1,T arg2);
public abstract T Divide(T arg1,T arg2);
public abstract T Multiply(T arg1,T arg2);
}
public class MyCalculator : BaseCalculator<int>
{
public override int Add(int arg1, int arg2)
{
return arg1 + arg2;
}
//Rest of the methods
}
A generic interface will yield a somewhat cleaner solution as well:
public interface ICalculator<T>
{
T Add(T arg1,T arg2);
//Rest of the methods
}
public class MyCalculator : ICalculator<int>
{
public int Add(int arg1, int arg2)
{
return arg1 + arg2;
}
//Rest of the methods
}
class ForInt
class ForLong
class ForByte...下去
谢谢
class For <T>
{
void Function()
{
T i;
if(typeof(T)==typeof("System.Int32")){
i=Int32.Parse(i.ToString())+1;
}else if(typeof(T)==typeof("System.Long")){
i=Long.Parse(i.ToString())+1;
}
}
}
不是为了泛型而泛型,呵呵
程序里有很多类,它们唯一区别就在类型上,所以想偷个懒。。
这个方法确实另类不过感觉已经失去了用泛型的意义:)
但还是谢谢你了