How to access objects in new {int a, string b}

I have a method

public Action FirstAction(object data)
{
}

I need to pass two variables to this class, which are different types, for example int, stringor any other type of object.

I read that I can do it

FirstAction( new{int a, string b} )

My question is: how to access two separated variables in a method FirstAction?

Note. I cannot change the settings objectto object[]or params object[]; this must be done with the current signature.

+4
source share
3 answers

Perhaps use the dynamic keyword?

public Action FirstAction(dynamic data){
     var v = (int)data.a;
}

: , - . , ( ).

+2

, :

public Action FirstAction(object data) { 
     dynamic dataAsDynamic = data;
     int a = dataAsDynamic.a;
     string b = dataAsDynamic.b;
}

, , - , . , , .

+9

You need to use reflection:

foreach (var property in data.GetType().GetProperties())
{
    if (!property.CanRead) continue;
    if (property.GetIndexParameters().Length > 0) continue;
    string name = property.Name;
    object value = property.GetValue(data, null);

    ...
}

or dynamic:

dynamic d = data;
int a = d.a;
string b = d.b;
...
+6
source

All Articles