大致的意思是这样:
我写了一个泛型类,里面有一个方法
public class Base<T> where T : new()
{
public static T GetReference(string loginName, string password)
{
T t = new T();
t.xxxMethod();
....
return t;
}
}
当然,其它的类来自于Base,即
public class Class1 : Base<CustomType1>
public class Class2 : Base<CustomType2>
也就是说继承的时候所有的T换成了相应的CustomType
现在的问题在于,xxxMethod()是所有CustomType包含的方法
但是,在泛型内,编译器并不知道T包含一个xxxMethod()方法,编译的时候会报错
我尝试将CustomType1和CustomType2从同一个包含xxxMethod()的基类CustomTypeBase里继承
然后将泛型类的定义改成
public class Base<T> where T : CustomTypeBase, new()
这下t.xxxMethod()是不报错了
但是在Class1和Class2里报错了
“CustomType1”必须可转换为“CustomTypeBase”才能用作泛型类型或方法
“CustomType2”必须可转换为“CustomTypeBase”才能用作泛型类型或方法
也就是我让CustomType1、CustomType1继承于CustomTypeBase,好像没奏效。
所以,就想请问大家如何、在哪里去定义这个xxxMethod()
让编译器知道T有这个方法
是不是我的方式有点问题。
有点肤浅的提问,请大家指教!
谢谢!
我写了一个泛型类,里面有一个方法
public class Base<T> where T : new()
{
public static T GetReference(string loginName, string password)
{
T t = new T();
t.xxxMethod();
....
return t;
}
}
当然,其它的类来自于Base,即
public class Class1 : Base<CustomType1>
public class Class2 : Base<CustomType2>
也就是说继承的时候所有的T换成了相应的CustomType
现在的问题在于,xxxMethod()是所有CustomType包含的方法
但是,在泛型内,编译器并不知道T包含一个xxxMethod()方法,编译的时候会报错
我尝试将CustomType1和CustomType2从同一个包含xxxMethod()的基类CustomTypeBase里继承
然后将泛型类的定义改成
public class Base<T> where T : CustomTypeBase, new()
这下t.xxxMethod()是不报错了
但是在Class1和Class2里报错了
“CustomType1”必须可转换为“CustomTypeBase”才能用作泛型类型或方法
“CustomType2”必须可转换为“CustomTypeBase”才能用作泛型类型或方法
也就是我让CustomType1、CustomType1继承于CustomTypeBase,好像没奏效。
所以,就想请问大家如何、在哪里去定义这个xxxMethod()
让编译器知道T有这个方法
是不是我的方式有点问题。
有点肤浅的提问,请大家指教!
谢谢!
解决方案 »
- 关于xml读取
- C# 想通过Sendmessage 发送消息使checkbox 选中
- 在while循环中,break,continue,return有什么区别???
- C# datagridview 怎么自动调整行高 和 列宽
- WPF从数据库读取图片路径如何绑定到前台?
- [求助]向各位请教一个.net 2003安装部署的问题
- 电子书交换,我有敏捷软件开发-原则模式与实践的中文版电子书,有意的朋友请进入
- 怎样在wpf多点触控系统中浏览office,顶者有分!
- 在VS.net中,编写一个宏,如何在宏的执行过程中禁用VS.net的自动完成功能? -=200分=-
- 编译下面的几行程序为什么会出现下面的错误?请指教,谢谢!
- 接口的用途不是很清楚,请高手给讲讲
- 散分拉!在使webform里如何使鼠标移到datagrid某一单元格上时显示成手型
难道这样
public class Base<T> where T : (CustomTypeBase)CustomType1, new()
不过不能这样写的哈
我看了
好像可以
public class Base<T> where T : CustomTypeBase, new()
T t = new T();
Type myType = t.GetType();
myType.GetMethod("xxxMethod");
这样去在CustomTypeBase把xxxMethod()给揪出来
但是弄出来了 又该如何执行这个方法呢
t.xxxMethod();这样是无法找到方法的。
{
void xxxMethod();
}
public class Base<T> where T : IxxxMethod,new()
{
public static T GetReference(string loginName, string password)
{
T t = new T();
t.xxxMethod();
return t;
}
}