【发布时间】:2015-11-15 13:44:39
【问题描述】:
我有这个interface:
public interface ITestInterface
{
int TestInt { get; set; }
}
还有这个通用方法(带有T : class 约束):
public void Test<T>() where T : class
{
// DoSomething
}
还有这个电话:
Test<ITestInterface>();
当interface不是class(或者是吗?)时,所有东西都会编译和运行。
为什么会这样?
我第一次看到这个是在我的 WCF 代理类上:
public partial class TestServiceClient:
System.ServiceModel.ClientBase<TestNamespace.ITestService>, TestNamespace.ITestService
ClientBase<T> 有这个定义:
public abstract class ClientBase<TChannel> :
ICommunicationObject, IDisposable where TChannel : class
【问题讨论】:
-
接口不是一个类,而是一个契约,一个类的样子的承诺。因此,如果您有一个带有接口的声明,调用代码应该使用实现该接口的对象的实例。
-
@o_weisman - 谢谢,在谷歌上找不到。
-
@GolezTrol - 我知道。我刚刚在我的 WCF 代理客户端上看到了它并创建了一个简单的示例。我知道有更好的方法来实现这样的目标。谢谢。
-
@haim770 - 刚刚检查过 - 如果您使用结构实现,编译器将显示非引用类型错误。
标签: c# generics interface constraints