Is it possible to use "implicit" generic type parameters in c#
I have a generic type:
public class Source<T> where T : ISomeInterfac开发者_StackOverflow中文版e<X> //...
Now, my problem is, I really don't want to modify Source<T>
to Source<T,X>
, but I want to use X inside Source.
No, there's no way of expressing that. If you want to be able to refer to X
within Source
, it has to be a type parameter.
Bear in mind that T
could implement (say) ISomeInterface<string>
and ISomeInterface<int>
. What would X
be in that case?
If you're using a generic type, you're telling the compiler that you're going to provide the actual type when creating a concrete instance. With your code, if you tried to do a
Source<string> s = new Source<string>();
the compiler would know that T is actually a string in the class, but you're not giving the compiler any info on what X would be. However, depending on what you want to do, you may be able to use a "has a" relationship with Interface with a naked type constraint instead of using inheritance. The following code does compile, for instance:
public interface ISomeInterface<X>
{
void SomeMethod(X someparam);
}
public class Source<T>
{
public void MyMethod<X>(ISomeInterface<X> someConcreteInstance) where X:T
{
}
}
精彩评论