命名空间范围内的别名泛型C# [英] Namespace scoped aliases for generic types in C#

查看:220
本文介绍了命名空间范围内的别名泛型C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们下面的例子:

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
}



编译器说:

The compiler says:

的类型参数的方法
'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,
系统。 FUNC)无法
从使用中推断出来。尝试
指定类型参数
明确。

The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

这是因为,它不能转换酒吧 Func键< IList的< X>中INT,IDictionary的< Y,IList的< Z>>>

It's because, it cannot convert Bar to Func<IList<X>, int, IDictionary<Y, IList<Z>>>.

这将是巨大的,如果我可以创建类型命名空间范围类型别名泛型类型在C#。然后,我会定义酒吧不是作为一个代表,而是我把它定义为一个命名空间范围内的别名 Func键< IList的< X>中INT, IDictionary的< Y,IList的< Z>>>

It would be great if I could create type namespace scoped type aliases for generic types in C#. Then I would define Bar not as a delegate, but rather I would define it as an namespace scoped alias for Func<IList<X>, int, IDictionary<Y, IList<Z>>>.

public alias Bar = Func<IList<X>, int, IDictionary<Y, IList<Z>>>;



然后我可以还定义命名空间范围内的别名例如的IDictionary< Y,IList的< Z>>

而如果使用得当:),就会使代码更易读。现在,我有内联泛型类型和实际代码是没有得到很好的可读性:(

And if used appropriately:), it will make the code more readable. Now, I have to inline the generic types and the real code is not well readable:(

你有没有发现同样的烦恼:)?有没有什么好的理由,为什么它不是在C#3.0?或者没有很好的理由,它只是物质金钱和/或时间

Have you find the same trouble:)? Is there any good reason why it is not in C# 3.0? Or there is no good reason, it's just matter of money and/or time?

编辑:我知道,我可以使用使用,但它不namespace界定范围 - 不是那么方便了我的情况。

I know that I can use using, but it is not namespace scoped - not so convenient for my case.

EDIT2:见的按净莲评论他认为,结构类型也可能会解决这个问题。

See comment by Joren where he suggests that structural typing might also solve the problem.

推荐答案

您的运气了; using指令只影响其当前的文件。没有命名空间宽型走样机制。

You're out of luck; the using directive affects only its current file. There is no namespace-wide type aliasing mechanism.

这是一个相当频繁要求的功能,这点它。但是,这也是相对于一个确实增加了很多代表性的力量的语言,这是个反对它最好有的便利功能。这将是很好的事,但它不是优先列表的真高。

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.

这篇关于命名空间范围内的别名泛型C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆