Silverlight - Howto use the Action<T> Delegate as a method parameter
I have a bunch of metadata that I want to load before I render any pages开发者_如何学JAVA (the page content depends on the meta data). Looking at the Application_Startup method in the App.xaml.cs I can see that there is the line of code
WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);
This looks to be exactly what I want (the definition is:
public LoadUserOperation LoadUser(Action<LoadUserOperation> completeAction, object userState);
This method calls the "Action" when the operation is completed. How can I implement a similar approach for my LoadMetaData() method?
MetaDataClass
public static class MetaData
{
private static bool _modelEntitiesIsLoading;
private static TTASDomainContext _ttasContext;
static MetaData()
{
Initialize();
}
private static void Initialize()
{
_ttasContext = new TTASDomainContext();
}
public static void LoadData()
{
//Exit if currently loading, or there is no context
if (_modelEntitiesIsLoading || _ttasContext == null)
{
return;
}
_modelEntitiesIsLoading = true;
_ttasContext.ModelEntities.Clear();
var q = _ttasContext.GetModelEntityQuery();
_ttasContext.Load(_ttasContext.GetModelEntityQuery(), OnModelEntitiesLoaded, null);
}
private static void OnModelEntitiesLoaded(LoadOperation<ModelEntity> loadOperation)
{
if (loadOperation.Error != null)
{
//raise an event...
}
else
{
ModelEntities = loadOperation;
_modelEntitiesIsLoading = false;
}
OK, so Action is simply a shorthand for a void
method taking one parameter of type T
. It is defined as:
public delegate void Action<T>(T obj);
So when you define a function taking an Action as a parameter you can simply call it as though it is a delegate:
public void LoadMetaData (Action<MetaDataOperation> callback) {
//method implementation
callback(new MetaDataOperation());
}
In the above scenario MetaDataOperation
could be any type you want.
Having said that, I get the feeling this might not answer your question. In that case could you provide more detail as to what the problem is?
EDIT Right, so MetaDataOperation
in this case is some sort of parameter that you want passed from LoadMetaData
method when it's complete. It is completely up to you as to what's in it. If you don't actually need it, you might as well not have it like so:
public void LoadMetaData (Action callback) {
//method implementation
callback();
}
//Use of LoadMetaData
public static void OnMetaDataFinished() {
System.Diagnostics.Debug.Trace("Finished loading metadata");
}
WhateverClass.LoadMetaData(OnMetaDataFinished);
//OR lambda version
WhateverClass.LoadMetaData(()=>System.Diagnostics.Debug.Trace("Finished loading metadata"));
精彩评论