简体   繁体   English

是否可以在c#中使用“隐式”泛型类型参数

[英]Is it possible to use “implicit” generic type parameters in c#

I have a generic type: 我有一个通用类型:

public class Source<T> where T : ISomeInterface<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. 现在,我的问题是,我真的不想将Source<T>修改to Source<T,X> ,但我想在Source中使用X.
Is it possible in any way? 有可能吗?

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. 如果您希望能够在Source引用X ,则它必须是类型参数。

Bear in mind that T could implement (say) ISomeInterface<string> and ISomeInterface<int> . 请记住, T可以实现(比方说) ISomeInterface<string> ISomeInterface<int> What would X be in that case? 在这种情况下X会是什么?

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. 编译器会知道T实际上是类中的一个字符串,但是你没有给编译器任何关于X的信息。 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
    {

    }        
}       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM