我收到编译错误:错误CS0535 'COITemplateWriter‘没有为以下代码实现接口成员'iTemplateWriter.Write(iTemplateModel)’TemplateService:
public COITemplate Write(COITemplateModel model)
{
throw new NotImplementedException();
}上述方法的接口签名如下:
public interface iTemplateWriter
{
public iTemplate Write(iTemplateModel model);
}类型COITemplate实现iTemplate接口,类型COITemplateModel实现iTemplateModel接口,那么为什么这段代码会失败呢?如果接口需要方法返回实现iTemplate的任何内容并将实现iTemplateModel的任何内容作为参数进行编译,这不是很合理吗?
发布于 2021-05-21 05:24:11
你混淆了运行时允许你做的事情和编译器在编译时需要知道的事情。
这就是泛型在C#中的作用
看起来您想要一个接口iTemplateWriter,在该接口上,您希望能够使用此方法Write,该方法可以接受任何iTemplateModel并返回任何iTemplate
您可以通过两种方式完成此操作:
方法1-您可以在接口级别定义接口的实现者将使用哪种类型的iTemplateModel和哪种类型的iTemplate:
public interface iTemplateWriter<TTemplate, TTemplateModel>
where TTemplate : iTemplate
where TTemplateModel : iTemplateModel
{
TTemplate Write(TTemplateModel model);
}这样做将允许您定义使用COITemplate和COITemplateModel的COITemplateWritter
public class COITemplateWritter : iTemplateWriter<COITemplate, COITemplateModel>
{
public COITemplate Write(COITemplateModel model)
{
throw new System.NotImplementedException();
}
}如果您在编译时知道实现类需要使用的类类型,请使用方法1
如果您需要实现类在运行时处理所有类型,并且您不知道编译时的类型,则使用方法2:
方法2-您可以在方法级别定义该方法将使用哪种类型的iTemplate和哪种类型的iTemplateModel。这将要求所有实现类能够返回在运行时传入的任何类型,这允许更多的灵活性,但在编译时结构化较少。
public interface iTemplateWriter
{
TTemplate Write<TTemplate, TTemplateModel>(TTemplateModel model)
where TTemplate : iTemplate
where TTemplateModel : iTemplateModel;
}
public class COITemplateWritter : iTemplateWriter
{
public TTemplate Write<TTemplate, TTemplateModel>(TTemplateModel model)
where TTemplate : iTemplate
where TTemplateModel : iTemplateModel
{
throw new System.NotImplementedException();
}
}发布于 2021-05-21 05:09:50
如果没有看到COITemplate的其余部分,假设它不是一个接口,那么您应该只需要让函数返回接口类型本身。
public iTemplateWriter Write(COITemplateModel model)
{
// if the "COITemplateModel" class is an iTemplateWriter you could just return that back.
return model;
// OR if some other object you are working with is that interface.
return (iTemplateWrite)OfWhateverClassYouAreTrying;
}https://stackoverflow.com/questions/67627878
复制相似问题