简体   繁体   中英

Is it possible to define parametrized type aliases in C#?

The C# documentation recommends the using directive to bring types into local scope. Indeed, I can do something like:

using DD = IDictionary<string,IDictionary<string,Blah>>;

and it works fine. However, I would like to be able to do:

using DD<Blah> = IDictionary<string,IDictionary<string,Blah>>

But the compiler dies at:

using DD<Blah...
        ^ ; expected

Is there a way to express such a type synonym, instead of repeating horrendously long generic names all over the place?

Context

I wanted to know if it was possible to write a generic, recursive wrapper on the output type of read-only collection. With the following interface

interface IIndexable<in In, out Out> { Out this[In idx] { get; }}

I managed to write

IIndexable<Key,VOut> map(IIndexable<Key,VIn> coll, Func<VIn, VOut> f)

I guess I'm really trying to emulate the convenience of Haskell's Functor typeclass.

So, wrapping my complex type in a custom class will not cut it, as it is being assembled from a stack of map() s and there is no single new call to replace with a custom wrapper class.

It would be better to introduce your own type for IDictionary<string, Blah> at least for the sake of readability.

The simplest class MyDic: Dictionary<string, Blah> {} will go. And you are free of aliases and long names. Just IDictionary<string, MyDic> .

If to answer to your question exactly. No, C# requires you to fully qualify your aliases.

Sadly, no. You'd have to define an alias for each Blah type (in your example).

Like:

using DB = IDictionary<string,IDictionary<string,Blah>>;
using DG = IDictionary<string,IDictionary<string,Gah>>;

I know, kinda frustrating.

( However , I would encourage you to consider whether you really want code that's dealing with variables typed as IDictionary<string, IDictionary<string, Blah>> in the first place. When you're nesting data structures like that, it's a good time to ask yourself whether you should be encapsulating some of that in a custom class that actually makes it easy to do what you want without giving yourself a headache. Of course, it may be that you're asking this question specifically because you're writing such a class, in which case, carry on.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM