I want the system can auto convert value depends on type of input value by using dictionary.
But the code below will show the error message.
cannot convert object into void
How can I make this work?
public class testClass
{
public int? TESTNULLABLEINT { get; set; }
public int TESTINT { get; set; }
public string TESTSTRING { get; set; }
public float TESTFLOAT { get; set; }
public MailAddress TESTMAIL { get; set; }
public bool TESTBOOL { get; set; }
}
static void Main(string[] args)
{
var TypeMapping = new Dictionary<Type, Action<string>>();
TypeMapping.Add(typeof(int), (x) => Convert.ToInt32(x));
TypeMapping.Add(typeof(int?), (x) => Convert.ToInt32(x));
TypeMapping.Add(typeof(float), (x) => Convert.ToSingle(x));
TypeMapping.Add(typeof(float?), (x) => Convert.ToSingle(x));
TypeMapping.Add(typeof(MailAddress), (x) => new MailAddress(x));
TypeMapping.Add(typeof(bool), (x) => Convert.ToBoolean(Convert.ToInt32(x)));
List<string> inputValue = new List<string>();
inputValue.Add(null);
inputValue.Add("100");
inputValue.Add("test");
inputValue.Add("0.2");
inputValue.Add("test@test.com");
inputValue.Add("1");
testClass test = new testClass();
int cnt = 0;
foreach (PropertyInfo item in test.GetType().GetProperties())
{
//"cannot convert object into void"
item.SetValue(test, TypeMapping[item.PropertyType](inputValue[cnt]));
cnt = cnt + 1;
}
}