让我们举个例子:
public class X { }
public class Y { }
public class Z { }
public delegate IDictionary<Y, IList<Z>> Bar(IList<X> x, int i);
public interface IFoo
{
// ...
Bar Bar { get; }
}
public class Foo : IFoo
{
// ...
public Bar Bar
{
get
{
return null; //...
}
}
}
void Main()
{
IFoo foo; //= ...
IEnumerable<IList<X>> source; //= ...
var results = source.Select(foo.Bar); // <- compile error here
}
编译器说:
无法从用法中推断方法“System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)”的类型参数。尝试明确指定类型参数。
这是因为,它无法转换Bar
为Func<IList<X>, int, IDictionary<Y, IList<Z>>>
.
如果我可以在 C# 中为泛型类型创建类型命名空间范围的类型别名,那就太好了。然后我不会将其定义Bar
为委托,而是将其定义为Func<IList<X>, int, IDictionary<Y, IList<Z>>>
.
public alias Bar = Func<IList<X>, int, IDictionary<Y, IList<Z>>>;
然后我还可以为 eg 定义命名空间范围的别名IDictionary<Y, IList<Z>>
。
如果使用得当:),它将使代码更具可读性。现在,我必须内联泛型类型,而真正的代码可读性不好:(
你有没有遇到同样的麻烦:)?有什么好的理由为什么它不在 C# 3.0 中?或者没有充分的理由,只是金钱和/或时间的问题?
编辑:我知道我可以使用using
,但它不是命名空间范围内的 - 对我来说不太方便。
EDIT2:参见Joren 的评论,他建议结构类型也可以解决问题。