Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c# - What is the syntax for creating a Dictionary with values as instances of Action<T>?

I need to create a Dictionary object as a member field
key = string
value = an instance of Action<T> where T could be different per entry, e.g. long, int, string (a ValueType or a RefType)

However can't get the compiler to agree with me here.. To create a member field it seems to need a fixed T specification. I've passed my limit of struggle time before awareness that 'It shouldn't be this difficult'

Might be a generics noob mistake. Please enlighten..

The usage would be something like this

m_Map.Add("Key1", 
   new delegate(long l) {Console.Writeline("Woohoo !{0}", l.ToString();));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't, basically. How would the compiler know what type you were interested in for any particular entry?

You can't even explain a relationship of Dictionary<Type, Action<T>> where each dictionary entry has a key which is a type and an action which uses that type. Generics just doesn't support that relationship.

If you will know the kind when you try to use it, you can just make it a Dictionary<string, Delegate> and cast the value when you fetch it. Alternatively, you could use Action<object> and live with the boxing and cast you'll end up with.

Note that to use anonymous methods or lambda expressions with just Delegate, you'll need to cast - or write a handy conversion method:

public static Delegate ConvertAction<T>(Action<T> action)
{
    return action;
} 

That way you can write:

Delegate dlg = ConvertAction((long x) => Console.WriteLine("Got {0}", x));

or in the dictionary context:

var dict = new Dictionary<string, Delegate>();
dict["Key1"] = ConvertAction((long x) => Console.WriteLine("Got {0}", x));

You'll still need to cast to the right type when you fetch the value out of the dictionary again though...

A different tack...

Instead of exposing a dictionary directly, you could encapsulate the dictionary in your own type, and have a generic Add method:

public void Add<T>(string key, Action<T> action)

So it would still be a Dictionary<string, Delegate> behind the scenes, but your type would make sure that it only contained values which were delegates taking a single argument.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...