【发布时间】:2017-08-04 13:11:21
【问题描述】:
我发现了这个问题: Is it possible to specify a generic constraint for a type parameter to be convertible FROM another type? 我正在寻找更聪明的方法。
Class A {
public A(string){}
}
Class foo
{
private List<A> content = new List<A>();
public void Add(A a){
content.Add(a);
}
public void Add(string str){
content.Add(new A(str));
}
public void AddRange<T>(IEnumerable<T> iterable) // where T : ???
{
foreach(T t in iterable)
content.Add((A)t); //Error
}
}
错误是:
无法将类型“T”转换为“A”
问题:是否存在像“convertable”这样的where T : ? 表达式?
更新:
我有两个方法重载:
Add(A)和Add(string)
目前我尝试将 T 转换为 A。但我的主要问题是,我想使用与 T 相关的不同 Addmethods。
我需要的是这样的:
public void AddRange<T>(IEnumerable<T> iterable) where T : Add(T)
{
foreach (T t in iterable)
this.Add(t);
}
【问题讨论】:
-
不清楚您要达到的目标。你不想要
where T : A吗? -
“可转换”是什么意思?
-
我想用两种不同的可枚举类型调用 Add:List 和 List
。 -
-
@Rahul,我做到了,但错误仍然存在。但
T可能就是一切。例如整数是不可转换的。所以错误是可以的。我需要限制T来解决它。我不知道该怎么说:T是所有可以转换(impl/expl)为A的类型。
标签: c# generics ienumerable