c# - 是否可以对 List<Interface> 施加类型约束?

标签 c# .net

在我的类里面,我有

class MyClass : IMyInterface
{

//I want MyClass only to be able to accept object of type List<SomethingElse>
public List<ISomething> ListOfSomethings {get; set;}

}

interface IMyInterface{

List<ISomething> ListOfSomethings {get; set;}

}

class SomethingElse : ISomething{

}

class SomethingMore : Isomething{

}

基本上我想知道是否可以限制列表在 MyClass 中使用的类型,所以如果有人尝试将其编码为错误的类型(即,SomethingMore 的列表),它会抛出异常。

编辑:如果无法做到这一点,是否有可行的替代解决方案?

最佳答案

您可以约束 T (类型)列表项(和任何其他 T )使用 where限制:

更多详情见Constraints on Type Parameters

接口(interface) :

interface ISomething { }

只允许使用 T实现接口(interface)ISomething的s .
interface IMyInterface<T> where T : ISomething
{
    List<T> ListOfSomethings { get; set; }
}

类(class) :
class SomethingElse : ISomething { }

class SomethingMore : ISomething { }

class MyClass1 : IMyInterface<SomethingElse>
{
    public List<SomethingElse> ListOfSomethings { get; set; }
}

class MyClass2 : IMyInterface<SomethingMore>
{
    public List<SomethingMore> ListOfSomethings { get; set; }
}

您可以限制 T任何适合你的地方。这里以类本身为例。
这仅允许 SomethingElse
class MyClass3<T> : IMyInterface<T> where T : SomethingElse
{
    public List<T> ListOfSomethings { get; set; }
}

带有 Dictionary 的示例:
var dic = new Dictionary<string, IMyInterface<ISomething>>();
dic.Add("MyClass1", (IMyInterface<ISomething>)new MyClass1());
dic.Add("MyClass2", (IMyInterface<ISomething>)new MyClass2());

如果您不会每次都转换它,那么我目前能想到的唯一解决方案是创建您的自定义字典并封装转换:
class MyDictionary : Dictionary<string, IMyInterface<ISomething>>
{
    public void Add(string key, MyClass1 value)
    {
        base.Add(key, (IMyInterface<ISomething>)value);
    }

    public void Add(string key, MyClass2 value)
    {
        base.Add(key, (IMyInterface<ISomething>)value);
    }
}

var dic2 = new MyDictionary();
dic2.Add("MyClass1", new MyClass1());
dic2.Add("MyClass2", new MyClass2());

关于c# - 是否可以对 List<Interface> 施加类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696486/

相关文章:

C# 预定义类型 'System.Object' 未定义或导入

c# - 为什么仅在实现接口(interface)后才重写方法?

c# - 如何判断基于套接字的客户端中的连接是否已断开?

c# - C++/CLI 中 C# 类的显式类型转换

c# - 在 C# 中使用 SendKeys 发送 ctrl-space?

c# - 如何判断 Socket 的发送缓冲区中有多少数据

c# - 如何在 C# 中更新数据源

c# - 通过 websocket 连接同步集合

c# - 将字符串中的 JSON 日期替换为更易读的日期

c# - 服务器上的全局自定义类