7

让我们举个例子:

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)”的类型参数。尝试明确指定类型参数。

这是因为,它无法转换BarFunc<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 的评论,他建议结构类型也可以解决问题。

4

2 回答 2

9

你运气不好;using 指令仅影响其当前文件。没有名称空间范围的类型别名机制。

This is a fairly frequently requested feature, which is points for it. But it is also a "nice to have" convenience feature as opposed to one that really adds lots of representational power to the language, which is points against it. It would be nice to do, but it's not really high on the priority list.

于 2010-04-07T15:18:40.577 回答
0

如果你这样做...

var results = source.Select((x, i) => foo.Bar(x, i));

它可以为您找出类型,而无需明确指定它们。

(诚​​然,这与其说是解决方案,不如说是一种变通方法)

于 2010-04-07T08:11:38.293 回答