c# - 使用另一个接口(interface)属性的 IList 实现接口(interface)的类...如何?

标签 c# class interface properties ilist

我有两个这样的接口(interface):

public interface IMyInterface1
{
    string prop1 { get; set; }
    string prop2 { get; set; }
}

public interface IMyInterface2
{
    string prop1 { get; set; }
    IList<IMyInterface1> prop2 { get; set; }
}

我定义了两个实现接口(interface)的类:

public class MyClass1 : IMyInterface1
{
     public string prop1 {get; set;}
     public string prop2 {get; set;}
}

public class MyClass2 : IMyInterface2
{
     public string prop1 {get; set;}
     public IList<MyClass1> prop2 {get; set;}
}

但是当我构建代码时出现以下错误消息:

“ClassLibrary1.MyClass2”没有实现接口(interface)成员“ClassLibrary1.IMyInterface2.prop2”。 “ClassLibrary1.MyClass2.prop2”无法实现“ClassLibrary1.IMyInterface2.prop2”,因为它没有匹配的“System.Collections.Generic.IList”返回类型

如何在我的类上实现 IMyInterface2 的“IList prop2”?

最佳答案

您的接口(interface)要求实现类提供类型为 IList<IMyInterface1> 的属性, 不是 IList<class that implements IMyInterface1> .

您需要制作 IMyInterface2通用的,如果你想让它工作:

public interface IMyInterface2<T> where T : IMyInterface1
{
    string prop1 { get; set; }
    IList<T> prop2 { get; set; }
}

然后MyClass2变成:

public class MyClass2 : IMyInterface2<MyClass1>
{
     public string prop1 {get; set;}
     public IList<MyClass1> prop2 {get; set;}
}

关于c# - 使用另一个接口(interface)属性的 IList 实现接口(interface)的类...如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3676708/

相关文章:

C#/.NET - 如何在我的应用程序中允许 HTTPS 的 "custom"Root-CA(仅)?

c# - 如何重构此 C# 代码

c++ - 从子类中调用类函数

kotlin - 在 Kotlin 中实现接口(interface)

c# - IComparable 不需要逆变?

java - 在 Java 中继承泛型接口(interface)

C# Word 文档中的分栏符

c# - Entity Framework ,防止重复记录,同时连接

Java 对列表

c# - 静默安装