为复杂类型创建别名而无需子类化? [英] Create an alias for a complex type without subclassing?

查看:78
本文介绍了为复杂类型创建别名而无需子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有一个复杂的类型,导致行长非常长.在这里:

I have a complex type in my program that results in very long line lengths. Here it is:

List<FruitCallback<Fruit>>

这是代码行太长且令人困惑的示例:

Here's an example of where the line of code is simply too long and confusing:

private static Dictionary<Type, List<FruitCallback<Fruit>>> callbacks = new Dictionary<Type, List<FruitCallback<Fruit>>>();

我可以通过将其子类化来为其创建别名:

I can create an alias for it by subclassing it like so:

class FruitCallbacks : List<SomeClass.FruitCallback<Fruit>> { }

但是我发誓我记得在某处读过某种别名这样的东西的方式,这样就不需要一个空的类了.

But I could of sworn I remember reading somewhere about a way to alias something like this such that an empty class would not be necessary.

推荐答案

您可以在您的类文件中添加完全合格的 using 语句(在using指令部分)给类起别名.有点冗长.

You can add a fully qualified using statement to your class file (in the using directives section) to alias the class. It's a bit verbose.

using MyType = System.Collections.Generic.List<YourNamespace.FruitCallback<YourNamespace.Fruit>>;

然后您可以在代码中使用 MyType 代替 List< FruitCallback< Fruit>> .

And then you can MyType in place of List<FruitCallback<Fruit>> in your code.

完整的工作示例.

// aliased outside the namespace
using MyList = System.Collections.Generic.List<Bar.FruitCallBack<Bar.Fruit>>;

namespace Bar
{
    // alternately, can be aliased inside the namespace 
    // using MyList = System.Collections.Generic.List<FruitCallBack<Fruit>>;        

    class Program
    {
        static void Main()
        {
            var myList = new MyList();
        }
    }

    public class FruitCallBack<T> { }
    public class Fruit { }
}

这篇关于为复杂类型创建别名而无需子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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