I'm trying to do this with this examples:
public void Method1(object someClassAsTSender, object parameter)
{
//i think parametertype = parameter...
MessagingCenter.Subscribe<someClassAsTSender, parametertype> (this, "messageKey", (message, args) =>
{
Device.BeginInvokeOnMainThread(async () =>
{
//await do;
});
}
);
}
or
public void Method2(object someClassAsTSender, object parameter)
{
//i think parametertype = parameter...
MessagingCenter.Subscribe<someClassAsTSender, parametertype> (this, "messageKey", (message, args) =>
{
//do;
}
);
}
I tryied to use GetType().Name, typeof(), but no have idea how i solve this.
It's just a doubth, because to MVVM i considerate an use of Framework more interestant.
If it is not correct to use MessagingCenter in this way, please explain.
public static void Subscribe<TSender,TArgs> (object subscriber, string message, Action<TSender,TArgs> callback, TSender source = null) where TSender : class;
TArgs is the type of the objects that are used as message arguments for the messageļ¼but you could not use typeof or GetType to set it.you could set it to object like :
public void Method1(object someClassAsTSender, object parameter)
{
//i think parametertype = parameter...
MessagingCenter.Subscribe<someClassAsTSender, object> (this, "messageKey", (message, args) =>
{
//convert the type (e.g string data = args as string)
Device.BeginInvokeOnMainThread(async () =>
{
//await do;
});
}
);
}
Related
How do I create a Dictionary where I can store functions?
Thanks.
I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:
private void functionName(arg1, arg2, arg3)
{
// code
}
dictionaryName.add("doSomething", functionName);
private void interceptCommand(string command)
{
foreach ( var cmd in dictionaryName )
{
if ( cmd.Key.Equals(command) )
{
cmd.Value.Invoke();
}
}
}
However, the function signature is not always the same, thus having different amount of arguments.
Like this:
Dictionary<int, Func<string, bool>>
This allows you to store functions that take a string parameter and return boolean.
dico[5] = foo => foo == "Bar";
Or if the function is not anonymous:
dico[5] = Foo;
where Foo is defined like this:
public bool Foo(string bar)
{
...
}
UPDATE:
After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.
And here's another alternative:
class Program
{
static void Main()
{
// store
var dico = new Dictionary<int, Delegate>();
dico[1] = new Func<int, int, int>(Func1);
dico[2] = new Func<int, int, int, int>(Func2);
// and later invoke
var res = dico[1].DynamicInvoke(1, 2);
Console.WriteLine(res);
var res2 = dico[2].DynamicInvoke(1, 2, 3);
Console.WriteLine(res2);
}
public static int Func1(int arg1, int arg2)
{
return arg1 + arg2;
}
public static int Func2(int arg1, int arg2, int arg3)
{
return arg1 + arg2 + arg3;
}
}
With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.
However, the function signature is not
always the same, thus having different
amount of arguments.
Let's start with a few functions defined like this:
private object Function1() { return null; }
private object Function2(object arg1) { return null; }
private object Function3(object arg1, object arg3) { return null; }
You really have 2 viable options at your disposal:
1) Maintain type-safety by having clients call your function directly.
This is probably the best solution, unless you have very good reasons for breaking from this model.
When you talk about wanting to intercept function calls, it sounds to me like you're trying to re-invent virtual functions. There's a boat load of ways to get this sort of functionality out of the box, such as inheriting from a base class an overriding its functions.
It sounds to me like you want a class that's more of a wrapper than a derived instance of a base class, so do something like this:
public interface IMyObject
{
object Function1();
object Function2(object arg1);
object Function3(object arg1, object arg2);
}
class MyObject : IMyObject
{
public object Function1() { return null; }
public object Function2(object arg1) { return null; }
public object Function3(object arg1, object arg2) { return null; }
}
class MyObjectInterceptor : IMyObject
{
readonly IMyObject MyObject;
public MyObjectInterceptor()
: this(new MyObject())
{
}
public MyObjectInterceptor(IMyObject myObject)
{
MyObject = myObject;
}
public object Function1()
{
Console.WriteLine("Intercepted Function1");
return MyObject.Function1();
}
public object Function2(object arg1)
{
Console.WriteLine("Intercepted Function2");
return MyObject.Function2(arg1);
}
public object Function3(object arg1, object arg2)
{
Console.WriteLine("Intercepted Function3");
return MyObject.Function3(arg1, arg2);
}
}
2) OR map the input of your functions to a common interface.
This might work if all of your functions are related. For example, if you're writing a game, and all the functions do something to some part of the player or player's inventory. You'd end up with something like this:
class Interceptor
{
private object function1() { return null; }
private object function2(object arg1) { return null; }
private object function3(object arg1, object arg3) { return null; }
Dictionary<string, Func<State, object>> functions;
public Interceptor()
{
functions = new Dictionary<string, Func<State, object>>();
functions.Add("function1", state => function1());
functions.Add("function2", state => function2(state.arg1, state.arg2));
functions.Add("function3", state => function3(state.arg1, state.are2, state.arg3));
}
public object Invoke(string key, object state)
{
Func<object, object> func = functions[key];
return func(state);
}
}
Define the dictionary and add the function reference as the value, using System.Action as the type:
using System.Collections;
using System.Collections.Generic;
public class Actions {
public Dictionary<string, System.Action> myActions = new Dictionary<string, System.Action>();
public Actions() {
myActions ["myKey"] = TheFunction;
}
public void TheFunction() {
// your logic here
}
}
Then invoke it with:
Actions.myActions["myKey"]();
Hey, I hope this helps. What language are you coming from?
internal class ForExample
{
void DoItLikeThis()
{
var provider = new StringMethodProvider();
provider.Register("doSomethingAndGetGuid", args => DoSomeActionWithStringToGetGuid((string)args[0]));
provider.Register("thenUseItForSomething", args => DoSomeActionWithAGuid((Guid)args[0],(bool)args[1]));
Guid guid = provider.Intercept<Guid>("doSomethingAndGetGuid", "I don't matter except if I am null");
bool isEmpty = guid == default(Guid);
provider.Intercept("thenUseItForSomething", guid, isEmpty);
}
private void DoSomeActionWithAGuid(Guid id, bool isEmpty)
{
// code
}
private Guid DoSomeActionWithStringToGetGuid(string arg1)
{
if(arg1 == null)
{
return default(Guid);
}
return Guid.NewGuid();
}
}
public class StringMethodProvider
{
private readonly Dictionary<string, Func<object[], object>> _dictionary = new Dictionary<string, Func<object[], object>>();
public void Register<T>(string command, Func<object[],T> function)
{
_dictionary.Add(command, args => function(args));
}
public void Register(string command, Action<object[]> function)
{
_dictionary.Add(command, args =>
{
function.Invoke(args);
return null;
} );
}
public T Intercept<T>(string command, params object[] args)
{
return (T)_dictionary[command].Invoke(args);
}
public void Intercept(string command, params object[] args)
{
_dictionary[command].Invoke(args);
}
}
The following scenario would allow you to use a dictionary of elements to send in as input parameters and get the same as the output parameters.
First add the following line at the top:
using TFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IDictionary<string, object>>;
Then inside your class, define the dictionary as follows:
private Dictionary<String, TFunc> actions = new Dictionary<String, TFunc>(){
{"getmultipledata", (input) =>
{
//DO WORKING HERE
return null;
}
},
{"runproc", (input) =>
{
//DO WORKING HERE
return null;
}
}
};
This would allow you to run these anonymous functions with a syntax similar to this:
var output = actions["runproc"](inputparam);
Why not use params object[] list for method parameters and do some validation inside either your methods (or calling logic), It will allow for a variable number of parameters.
I have the following code:
private void StartTask<T>(string parameter)
{
dynamic instance = (T) Activator.CreateInstance(typeof(T), parameter);
Task.Factory.StartNew(() => instance.DoCompare());
}
This does not work and the "DoCompare()" method does not get called...How do I call a method in a class with parameters in a generic type method?
Class I am initiating:
public class Something {
private string _parameter;
public Something(string parameter) {
_parameter = parameter;
}
public void DoCompare(){
//Do longrunning task
}
}
EDIT: Removed constraint BaseClass5 because of confusion
EDIT2: I get: A first chance exception of type
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'
EDIT3:
This seems to work, the issue seems to be Task.Factory.StartNew:
private void StartTaskAwesomium<T>() where T
{
dynamic instance = (T) Activator.CreateInstance(typeof (T), parameter);
instance.Test();
}
In theory your code should work, but it is a "fire-and-forget" pattern, meaning it will be executed sometime, but you have no control over that or can check if it actually was executed or if there was an exception.
Maybe change it to:
private async void StartTask<T>(string parameter) where T : BaseClass5
{
BaseClass5 instance = (T)Activator.CreateInstance(typeof(T), parameter);
await Task.Factory.StartNew(() => instance.DoCompare());
}
No need for the dynamic as because of your generic constraint you know that T must be BaseClass5 or based on it.
Or return the task to await (or task.Wait()) it elsewhere:
private Task StartTask<T>(string parameter)
{
T instance = (T)Activator.CreateInstance(typeof(T), parameter);
return Task.Factory.StartNew(() => instance.DoCompare());
}
The solution was to wrap the creation of the class in the Task itself like this:
private void StartTask<T>(string connectionId) where T : BaseClass5
{
Task.Factory.StartNew(() =>
{
dynamic instance = (T) Activator.CreateInstance(typeof (T), connectionId);
instance.DoCompare();
});
}
private void StartTask<T>(string parameter)
{
dynamic instance = (T) Activator.CreateInstance(typeof(T), parameter);
Task.Factory.StartNew(() => {instance.DoCompare();});
}
This seems to work.
I want to compile this WPF code and get this error.
public void SetContentObject(Type contentType)
{
this.Dispatcher.BeginInvoke(delegate(Type input) //Error here <-
{
object obj = Activator.CreateInstance(input);
this.Content = obj;//this.Content declared as object
}, new object[]
{
contentType
});
}
Edit 1:
Using .NET 3.5. 4.0 not allowed
Dispatcher.BeginInvoke() method should pass the delegate without parameters (see http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx). You can pass your parameter be declaring it outside your anaimous method. UPDATED
public void SetContentObject(Type contentType)
{
Type input;
Dispatcher.BeginInvoke(new Action(delegate
{
object obj = Activator.CreateInstance(input);
this.Content = obj;
}), new object[]
{
contentType
});
}
You might be confused with Invoke and BeginInvoke:
public void Invoke(Action callback, DispatcherPriority priority)
//no priority is allowed below.
public DispatcherOperation BeginInvoke(Action a)
I have a generic method
public delegate void Handler<T>(T val);
I enable users to register to events and provide this delegate.
I need to save the list of delegate according to their types.
I tried saving in a dictionary of Type and object. when adding the method I cast it to a
List<Handler<T>>
according to the T. but then when an event occurred I do not have the T so cannot cast to the relevant list of generic handlers (I do have the Type but not the T)
I solved this by saving methodInfo list for each type
private Dictionary<Type, List<MethodInfo>> handlers = new Dictionary<Type, List<MethodInfo>>();
public delegate void Handler<T>(T val);
public void Register<T>( Handler<T> handler )
{
List<MethodInfo> lst;
if (!handlers.TryGetValue(typeof(T), out lst))
{
lst = new List<MethodInfo>();
handlers.Add(typeof(T), lst);
}
lst.Add(handler.Method);
}
public void RaiseEvent( string value)
{
foreach (KeyValuePair<Type, List<MethodInfo>> pair in handlers)
{
object typedValue;
if (pair.Key.IsEnum)
{
typedValue = Enum.Parse(pair.Key, value);
}
else
{
typedValue = Convert.ChangeType(value, pair.Key);
}
foreach (MethodInfo methodInfo in pair.Value )
{
methodInfo.Invoke(null, new[] { typedValue });
}
}
}
}
but the problem is that this approach will work only if the method is static , otherwise it will require the type of class.
is there any solution for this problem???
enable generic events...
thanks!
Maybe this will help:
public delegate void Handler<in T>(T val);
private List<Delegate> m_list = new List<Delegate>();
public void AddListener<T>(Handler<T> handler) {
m_list.Add(handler);
}
public void Call(object eventArg) {
foreach (var handler in m_list) {
handler.DynamicInvoke(eventArg);
}
}
Then, if you have a handler like this:
private void MyHandler(int val) {
// Do something
}
You can add it to the list like this:
AddListener<int>(MyHandler);
(This assumes I correctly understood what you're trying to do. I'm not sure though.)
You could also make a handler repository using a non-generic delegate, something like:
public delegate void Handler(object val);
public delegate void Handler<T>(T val);
public class HandlerRepository
{
private Dictionary<Type, Handler> handlers = new Dictionary<Type, Handler>();
public void RegisterHandler<T>(Handler<T> handler)
{
//error checking omitted
//create a non-generic handler that calls the generic handler
//with the correct type.
handlers.Add(typeof(T), (value)=>handler((T)value));
}
public void ExecuteHandler<T>(T value)
{
//error checking ommited
handlers[typeof(T)](value);
}
}
and use it like this:
Handler<int> handleInt = value => Console.WriteLine("Int32 is {0}", value);
Handler<string> handleString = value => Console.WriteLine("String is {0}", value);
HandlerRepository repo = new HandlerRepository();
repo.RegisterHandler(handleInt);
repo.RegisterHandler(handleString);
//this call boxes the argument to an object
repo.ExecuteHandler(5); // "Int32 is 5"
repo.ExecuteHandler("Hello, world"); "String is Hello, world"
How do I create a Dictionary where I can store functions?
Thanks.
I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:
private void functionName(arg1, arg2, arg3)
{
// code
}
dictionaryName.add("doSomething", functionName);
private void interceptCommand(string command)
{
foreach ( var cmd in dictionaryName )
{
if ( cmd.Key.Equals(command) )
{
cmd.Value.Invoke();
}
}
}
However, the function signature is not always the same, thus having different amount of arguments.
Like this:
Dictionary<int, Func<string, bool>>
This allows you to store functions that take a string parameter and return boolean.
dico[5] = foo => foo == "Bar";
Or if the function is not anonymous:
dico[5] = Foo;
where Foo is defined like this:
public bool Foo(string bar)
{
...
}
UPDATE:
After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.
And here's another alternative:
class Program
{
static void Main()
{
// store
var dico = new Dictionary<int, Delegate>();
dico[1] = new Func<int, int, int>(Func1);
dico[2] = new Func<int, int, int, int>(Func2);
// and later invoke
var res = dico[1].DynamicInvoke(1, 2);
Console.WriteLine(res);
var res2 = dico[2].DynamicInvoke(1, 2, 3);
Console.WriteLine(res2);
}
public static int Func1(int arg1, int arg2)
{
return arg1 + arg2;
}
public static int Func2(int arg1, int arg2, int arg3)
{
return arg1 + arg2 + arg3;
}
}
With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.
However, the function signature is not
always the same, thus having different
amount of arguments.
Let's start with a few functions defined like this:
private object Function1() { return null; }
private object Function2(object arg1) { return null; }
private object Function3(object arg1, object arg3) { return null; }
You really have 2 viable options at your disposal:
1) Maintain type-safety by having clients call your function directly.
This is probably the best solution, unless you have very good reasons for breaking from this model.
When you talk about wanting to intercept function calls, it sounds to me like you're trying to re-invent virtual functions. There's a boat load of ways to get this sort of functionality out of the box, such as inheriting from a base class an overriding its functions.
It sounds to me like you want a class that's more of a wrapper than a derived instance of a base class, so do something like this:
public interface IMyObject
{
object Function1();
object Function2(object arg1);
object Function3(object arg1, object arg2);
}
class MyObject : IMyObject
{
public object Function1() { return null; }
public object Function2(object arg1) { return null; }
public object Function3(object arg1, object arg2) { return null; }
}
class MyObjectInterceptor : IMyObject
{
readonly IMyObject MyObject;
public MyObjectInterceptor()
: this(new MyObject())
{
}
public MyObjectInterceptor(IMyObject myObject)
{
MyObject = myObject;
}
public object Function1()
{
Console.WriteLine("Intercepted Function1");
return MyObject.Function1();
}
public object Function2(object arg1)
{
Console.WriteLine("Intercepted Function2");
return MyObject.Function2(arg1);
}
public object Function3(object arg1, object arg2)
{
Console.WriteLine("Intercepted Function3");
return MyObject.Function3(arg1, arg2);
}
}
2) OR map the input of your functions to a common interface.
This might work if all of your functions are related. For example, if you're writing a game, and all the functions do something to some part of the player or player's inventory. You'd end up with something like this:
class Interceptor
{
private object function1() { return null; }
private object function2(object arg1) { return null; }
private object function3(object arg1, object arg3) { return null; }
Dictionary<string, Func<State, object>> functions;
public Interceptor()
{
functions = new Dictionary<string, Func<State, object>>();
functions.Add("function1", state => function1());
functions.Add("function2", state => function2(state.arg1, state.arg2));
functions.Add("function3", state => function3(state.arg1, state.are2, state.arg3));
}
public object Invoke(string key, object state)
{
Func<object, object> func = functions[key];
return func(state);
}
}
Define the dictionary and add the function reference as the value, using System.Action as the type:
using System.Collections;
using System.Collections.Generic;
public class Actions {
public Dictionary<string, System.Action> myActions = new Dictionary<string, System.Action>();
public Actions() {
myActions ["myKey"] = TheFunction;
}
public void TheFunction() {
// your logic here
}
}
Then invoke it with:
Actions.myActions["myKey"]();
Hey, I hope this helps. What language are you coming from?
internal class ForExample
{
void DoItLikeThis()
{
var provider = new StringMethodProvider();
provider.Register("doSomethingAndGetGuid", args => DoSomeActionWithStringToGetGuid((string)args[0]));
provider.Register("thenUseItForSomething", args => DoSomeActionWithAGuid((Guid)args[0],(bool)args[1]));
Guid guid = provider.Intercept<Guid>("doSomethingAndGetGuid", "I don't matter except if I am null");
bool isEmpty = guid == default(Guid);
provider.Intercept("thenUseItForSomething", guid, isEmpty);
}
private void DoSomeActionWithAGuid(Guid id, bool isEmpty)
{
// code
}
private Guid DoSomeActionWithStringToGetGuid(string arg1)
{
if(arg1 == null)
{
return default(Guid);
}
return Guid.NewGuid();
}
}
public class StringMethodProvider
{
private readonly Dictionary<string, Func<object[], object>> _dictionary = new Dictionary<string, Func<object[], object>>();
public void Register<T>(string command, Func<object[],T> function)
{
_dictionary.Add(command, args => function(args));
}
public void Register(string command, Action<object[]> function)
{
_dictionary.Add(command, args =>
{
function.Invoke(args);
return null;
} );
}
public T Intercept<T>(string command, params object[] args)
{
return (T)_dictionary[command].Invoke(args);
}
public void Intercept(string command, params object[] args)
{
_dictionary[command].Invoke(args);
}
}
The following scenario would allow you to use a dictionary of elements to send in as input parameters and get the same as the output parameters.
First add the following line at the top:
using TFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IDictionary<string, object>>;
Then inside your class, define the dictionary as follows:
private Dictionary<String, TFunc> actions = new Dictionary<String, TFunc>(){
{"getmultipledata", (input) =>
{
//DO WORKING HERE
return null;
}
},
{"runproc", (input) =>
{
//DO WORKING HERE
return null;
}
}
};
This would allow you to run these anonymous functions with a syntax similar to this:
var output = actions["runproc"](inputparam);
Why not use params object[] list for method parameters and do some validation inside either your methods (or calling logic), It will allow for a variable number of parameters.