在我的类里面,我有
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/