how to set nullable type via reflection code ( c#)?

后端 未结 8 1396
我寻月下人不归
我寻月下人不归 2020-12-28 16:05

I need to set the properties of a class using reflection.

I have a Dictionary with property names and string values.

Inside

8条回答
  •  清歌不尽
    2020-12-28 16:27

    Originally, the best solution is mentioned at MSDN forum. However, when you need to implement dynamic solution, where you don't know exactly how many nullable fields may be declared on a class, you best bet is to check if Nullable<> type can be assigned to the property, which you inspect via reflection

    protected T initializeMe(T entity, Value value)
    {
      Type eType = entity.GetType();
      foreach (PropertyInfo pi in eType.GetProperties())
            {
                //get  and nsame of the column in DataRow              
                Type valueType = pi.GetType();                
                if (value != System.DBNull.Value )
                {
                 pi.SetValue(entity, value, null);
                }
                else if (valueType.IsGenericType && typeof(Nullable<>).IsAssignableFrom(valueType)) //checking if nullable can be assigned to proptety
                {
                 pi.SetValue(entity, null, null);
                }
                else
                {
                 System.Diagnostics.Trace.WriteLine("something here");
                }
                ...
            }
    ...
    }
    

提交回复
热议问题