Casting action <line> to action <object>

I need to pass Action<string>in Action<object>. Although this is not safe at all, in my case it will always be called with a string. I get this error:

Unable to cast object of type 'System.Action1[System.String]' to type 'System.Action 1 [System.Object]". >

Any clues? Reflection is fair play. Combining one delegate into another is not .

UPDATE: I created a new question in Creating an open delegate to set properties or getter with a better explanation of my problem and a solution that uses the packaging I want to improve

+3
source share
4 answers

, , , , , . CLR . . , ?

, , Action<object>, Action<string> . string, CLR , , .

, , , Action<string> string , object. string.

// Original Version
void Method(string str) {
  // Operate on the string
}

// Modified version
void Method(object obj) { 
  string str = (string)obj;
  // operate on the string
}
+1

-, . , , () . :

void method(String s)
{
  s.Trim();
}

, , s Trim.

, Action T. Action<string> Action<SubclassString> , string .

, # (, object string), InvalidCastException. .

EDIT: , .

+6

, . , , , - Action<string> Action<object>. , .

, , .

ConcurrentDictionary<Type, Action<object>> _actions = new ConcurrentDictionary<Type, Action<object>>();
Action<string> actionStr = s => Console.WriteLine(s);

var actionObj = new Action<object>(obj => { 
  var castObj = (V)Convert.ChangeType(obj, typeof(V)); actionStr(castObj); 
} );

_actions.TryAdd(typeof(string), actionObj);
+1

- , . , Object, MethodInfo , , , . , , :

Action<string> s;
Action<object> o;

object sTarget = s.Target;
object oTarget = o.Target;

MethodInfo sMethod = s.Method;
MethodInfo oMethod = o.Method;

// Time to invoke in a later time.
sMethod.Invoke(sTarget, new object[] { strVal });
oMethod.Invoke(oTarget, new object[] { objVal });

, . , , . , , ( ), .

0

Source: https://habr.com/ru/post/1772788/


All Articles