开发者

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

开发者 https://www.devze.com 2023-03-22 14:32 出处:网络
The C# documentation recommends the using directive to bring types into local scope. Indeed, I can do something like:

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 fi开发者_如何学JAVAne. 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.


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消