How can I pass the void returned extension method to the dynamic extension method?

I want to pass an extension method that returns void as a parameter to another extension method that returns dynamic.

public static void AddTo(this Object entity, Object parent) { parent.GetCollectionOf(entity).Add(entity); } public static dynamic And(this Object entity, Action method) { entity.method(parent); return entity; } 

I would like to use it something like this

 dynamic parent = MakeNew(parentType); dynamic entity = MakeNew(type).And(AddTo(parent)); 

I like to pass any void method to And() , but still return the object that it expanded. I hope the dynamic return type is not problematic.

What is the syntax for this kind of thing?

+4
source share
4 answers

Could you do it like this?

 myObjects .Where(d => d.true == true && d.Value == 77) .Update(e => { e.Value = 1; e.true = false; } ); 

Use my linq carefully, it can explode at any moment; -)

  /// <summary> /// Used to modify properties of an object returned from a LINQ query /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <param name="input">The source</param> /// <param name="updater">The action to perform.</param> public static TSource Update<TSource>(this TSource input, Action<TSource> updater) { if (!updater.IsNull() && !input.IsNull()) { updater(input); } return input; } 

To fully explain this:

  public DataRow DoSomething(DataRow dataRow) { //DoSomething return dataRow; } var query = from dataRow in myDataTable.Rows.Cast<DataRow>() where Double.TryParse(dataRow["Distance"].ToString(), out distance) && distance > (11) && distance <= 99 select dataRow.Update(f => DoSomething(f)); 
+1
source

Do I have your question right?

 dynamic entity = MakeNew(type).And(() => { AddTo(parent); }); 
+2
source

I suspect you really want this:

 public static void AddTo(this Object entity, Object parent) { parent.GetCollectionOf(entity).Add(entity); } public static dynamic And(this Object entity, Action<object> method) { method(entity); return entity; } dynamic entity = MakeNew(type).And(entity => entity.AddTo(parent)); 

Having said that, it is still unclear where parent starts from, starting with ...

0
source

I think C # is not yet "dynamic" enough to do what I think you need.

The And method will not work, since the entity parameter is of type object , so entity.method(parent) will not work. Even if you define entity as a dynamic type, C # will try to find a method called a "method" to call. You can do this in your example:

 public static dynamic And(this Object entity, Action method, object parameter) { method(entity, parameter); return entity; } 

and

 dynamic entity = MakeNew(type).And(AddTo, parameter); 
0
source

All Articles