C# 接口引用
我有一个疑问,我已经搜索了很多关于它,我没有找到任何可以解释的 我可以在类中有一个引用接口的属性,并使用DI填充这些属性。例如:C# 接口引用,c#,C#,我有一个疑问,我已经搜索了很多关于它,我没有找到任何可以解释的 我可以在类中有一个引用接口的属性,并使用DI填充这些属性。例如: public interface ITest { void DoSomething(); } public class Test { ITest _test; public Test(Itest _test) { this._test = test; } } 问题是,如果我有一个泛型接口,并且我的类没有使用
public interface ITest {
void DoSomething();
}
public class Test {
ITest _test;
public Test(Itest _test)
{
this._test = test;
}
}
问题是,如果我有一个泛型接口,并且我的类没有使用泛型,那么当我创建这些属性时,会引发编译错误
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;
}
}
公共接口测试{
空隙剂量测定(T参数);
}
公开课考试{
ITest _test;//错误(找不到类型)
公共测试(Itest\U测试)
{
本试验=试验;
}
}
这可能吗?您的
测试
类也需要是泛型的-否则就无法知道\u Test
变量所指的测试是什么类型的。您如何知道如何调用\u test.DoSomething()
?Test
的类型参数不必是t
,当然:
public class Test<TFoo> {
ITest<TFoo> _test;
public Test(ITest<TFoo> _test)
{
this._test = test;
}
}
这完全取决于你想要达到的目标
编辑:如注释中所述,如果您的Test
类没有使用依赖于t
的ITest
的任何方面,您可能需要创建一个非泛型基本接口:
public interface ITest {
void DoSomethingBland();
}
public interface ITest<T> : ITest {
void DoSomethingSpecific(T foo);
}
公共接口测试{
void DoSomethingBland();
}
公共接口ITest:ITest{
无效剂量特定物(T foo);
}
然后你可以让你的类仅仅依赖于非泛型的ITest
接口,而不是ITest
你的Test
类也需要是泛型的-否则就无法知道\u Test
变量所指的是什么类型的ITest
。您如何知道如何调用\u test.DoSomething()
?Test
的类型参数不必是t
,当然:
public class Test<TFoo> {
ITest<TFoo> _test;
public Test(ITest<TFoo> _test)
{
this._test = test;
}
}
这完全取决于你想要达到的目标
编辑:如注释中所述,如果您的Test
类没有使用依赖于t
的ITest
的任何方面,您可能需要创建一个非泛型基本接口:
public interface ITest {
void DoSomethingBland();
}
public interface ITest<T> : ITest {
void DoSomethingSpecific(T foo);
}
公共接口测试{
void DoSomethingBland();
}
公共接口ITest:ITest{
无效剂量特定物(T foo);
}
然后你可以让你的类只依赖于非泛型的ITest
接口,而不是ITest
或ITest
继承的非泛型ITest
。很好的解释@Jon Skeet,我问这个问题的原因是因为我正在创建一个新的windows窗体窗口,我使用泛型从基类继承。但是,当我将基类设置为接受泛型时,即FormBase:Form,设计器会引发一个错误,即“无法加载基类FormBase”。我已经找到了这些错误的解决方案,但没有一个对我有效:(无论如何,很好的解释,非常感谢使用泛型从我的基类继承
你能解释更多吗?这通常不是泛型的用途,因为C#支持类继承。例如:我创建了一个像这样的表单FormBase:Form
,用作基类。在真正使用的表单中,我会这样做这:Sales:FormBase
。这会导致设计器错误,当我从基类中删除时,设计器会正常加载。或者是ITest
继承自的非泛型ITest
。很好的解释@Jon Skeet,我问这个问题的原因是因为我正在创建一个新的windows窗体窗口,并且我正在使用泛型继承自我的基类。但当我将基类设置为接受泛型时,即FormBase:Form,设计器会引发一个错误,称“无法加载基类FormBase”。我已搜索了这些错误的解决方案,但没有一个适用于我:(无论如何,很好的解释,非常感谢使用泛型从我的基类继承
你能解释更多吗?这通常不是泛型的用途,因为C#支持类继承。例如:我创建了一个像这样的表单FormBase:Form
,用作基类。在真正使用的表单中,我会这样做这:Sales:FormBase
。这会导致设计器错误,当我从基类中删除时,设计器将正常加载。
public interface ITest {
void DoSomethingBland();
}
public interface ITest<T> : ITest {
void DoSomethingSpecific(T foo);
}