2012-04-19 92 views
1

我有以下的类和方法:如何在泛型的where子句中指定泛型类?

public class MyGenericClass<T> 
    where T : class 
{ 
} 

public class MyClass 
{ 
    public TGen MyMethod<TGen>(TGen myGenClass) 
     where TGen : MyGenericClass<T> 
     where T : class 
    { 
     return myGenClass; 
    } 
} 

然而,这给出了一个错误,因为它无法化解的MyMethod符号T。我宁愿不必有MyMethod<TGen, T>,因为它对我来说似乎有点多余。这可能吗?

+2

但是'MyMethod'中没有'T'类型的参数。我不明白你想要做什么。 – 2012-04-19 16:01:44

+0

我想有'公共TGen MyMethod (TGen myGenClass)其中TGen:MyGenericClass <>' – cm007 2012-04-19 16:03:01

+0

我再次,我不明白你想用'MyGenericClass <>'传达什么。你为什么认为'MyGenericClass'的类型参数会以任何方式被推断?推断出什么? – 2012-04-19 16:04:01

回答

2

如果你希望能够使用任何MyGenericClass实现您TGen类型,那么你需要创建要使用的MyGenericClass实现的基类(当然,这限制了您将为您的TGen实例获得的功能。

public class MyGenericClassBase { } 
public class MyGenericClass<T> : MyGenericClassBase { } 
public class MyClass<TGen> 
     where TGen: MyGenericClassBase 
{ 
    // Stuff 
} 
1

听起来像是你只是忘记包括T在泛型类型的该方法的列表:

public TGen MyMethod<TGen, T>(TGen myGenClass) 
    where TGen : MyGenericClass<T> 
    where T : class 
{ 
    return myGenClass; 
} 
3

您必须指定T之前,你可以在定义中使用它。编译器无法知道什么是T

所以你之前使用它(在方法级别,如下,或者在一流水平MyClass),你应该指定T

public class MyClass 
{ 
    public TGen MyMethod<TGen, T>(TGen myGenClass) 
     where TGen : MyGenericClass<T> 
     where T : class 
    { 
     return myGenClass; 
    } 
} 

你也可以使用一个具体的实现泛型类型在哪里条款:

public class MyClass 
{ 
    public TGen MyMethod<TGen>(TGen myGenClass) 
     where TGen : MyGenericClass<DateTime> 
    { 
     return myGenClass; 
    } 
}