C # Delegates & guid.newguid ()

I just started using C # this afternoon, so be a little gentle.

I am currently working on a type of "template engine" where one of the callbacks must generate a globally unique identifier. I use delegates to manage callbacks.

Currently, the code looks like this (although I also tried an anonymous function and return NewGuid directly without a variable):

static string UID(List<string> p) { string s = Guid.NewGuid().ToString(); return s; } 

Which, when called directly, works fine. However, if I try to call it through a delegate (added to StringDictionary via addCallback("generate UID", new CallbackWrapper(UID)) ), the program will generate the same GUID, no matter how many times I duplicate it; even though calling the method immediately before and after the event results in a unique identifier, as expected. I'v

Without a doubt, this is just something simple that I missed, inevitably resulting from the fact that I am relatively inexperienced in C #.

Any help would be appreciated.

Thanks.

Well, I now tried a dictionary with the same result.

CallbackWrapper is just a delegate, it is defined as:

 delegate string CallbackWrapper(List<string> parameters); 

The rest of the work is done in another class, which looks like this:

 class TemplateParser { private Dictionary<string, CallbackWrapper> callbackMap; public TemplateParser(string directivePrefix, string directiveSuffix) { ... callbackMap = new Dictionary<string,CallbackWrapper>(); } public TemplateParser() : this("<!-- {", "} -->") {} { callbackMap.Add(name, callback); } public string parse(string filename) { ... string replacement = callbackMap[directiveName](new List<string>(parameters.Split(new string[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries)); ... } } 

I removed most of the string processing code to save some space.

+6
c #
source share
3 answers

The problem is the calling code, not the code itself and the delegate.

Using delegates here definitely works if called correctly.

In addition, your code may be slightly simplified:

 static string UID(List<string> p) { return Guid.NewGuid().ToString(); } 

(The variable is completely redundant.)

+1
source share

use .invoke delegate The difference between calling a direct function and delegate.invoke is here http://social.msdn.microsoft.com/Forums/en/csharplanguage/thread/f629c34d-6523-433a-90b3-bb5d445c5587

0
source share

StringDictionary will automatically add your CallbackWrapper to the string, i.e. it will be run only once and save the output of CallbackWrapper.ToString (). This is probably not what you want.

Try using the dictionary <string, CallbackWrapper> instead.

0
source share

All Articles