Skip to main content
 首页 » 编程设计

c#之接口(interface)引用

2024年02月20日12Free-Thinker

我有一个疑问,我已经搜索了很多,但我没有找到任何可以解释的东西。

我可以在我的类中有一个引用接口(interface)的属性,并使用 DI 来填充这些属性。例如:

public interface ITest { 
    void DoSomething(); 
} 
 
public class Test { 
    ITest _test; 
 
    public Test(Itest _test) 
    { 
        this._test = test; 
    } 
} 

问题是,如果我有一个通用接口(interface),而我的类不使用泛型,当我创建这些属性时会引发编译错误

public interface ITest<T> { 
    void DoSomething(T parameter); 
} 
 
public class Test { 
    ITest<T> _test; //error (Type cant be found) 
 
    public Test(Itest<T> _test) 
    { 
        this._test = test; 
    } 
} 

这可能吗?

请您参考如下方法:

你的 Test类也需要是通用的 - 否则无法知道什么样的 ITest<T> _test变量指的是。你怎么知道如何调用_test.DoSomething() ? Test 的类型参数不必是 T ,当然:

public class Test<TFoo> { 
    ITest<TFoo> _test; 
 
    public Test(ITest<TFoo> _test) 
    { 
        this._test = test; 
    } 
} 

然后您将其构建为:

ITest<string> x = ...; 
Test<string> test = new Test<string>(x); 

类型安全会阻止你写:

Test<int> test = new Test<int>(x); 

因为你不能构建 Test<int>来自 ITest<string> .

或者,您的 Test类可能只需要采取一种特定的 ITest ,因此根本不是通用的:

public class Test { 
    ITest<Guid> _test; 
 
    public Test(ITest<Guid> _test) 
    { 
        this._test = test; 
    } 
} 

这完全取决于您要实现的目标。

编辑:如评论中所述,如果您的 Test类不使用 ITest<T> 的任何方面依赖T ,您可能想要创建一个非通用的基础接口(interface):

public interface ITest { 
    void DoSomethingBland(); 
} 
 
public interface ITest<T> : ITest { 
    void DoSomethingSpecific(T foo); 
} 

然后你可以让你的类只依赖于非泛型 ITest接口(interface)而不是 ITest<T> .