大致的意思是这样:  
我写了一个泛型类,里面有一个方法  
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有这个方法
是不是我的方式有点问题。  
有点肤浅的提问,请大家指教!  
谢谢!

解决方案 »

  1.   

    强制转换
    难道这样
    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();这样是无法找到方法的。
      

  2.   

    把xxxMethod()定义为一个接口..T实现这个接口就可以了.. public interface IxxxMethod
            {
               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;
                }
            }