mardi 17 mai 2022

FieldInfo.SetValue(): Object of type 'System.String' cannot be converted to type 'System.Int32'

Program Logic:

  • Define some default values for an Employee in the C# program
  • Read an XML file about different Employees
  • Use Reflections to go through all the fields of the DefaultAttributes class
  • If a field name is present as an attribute in an Employee's XML node then, override the default value with the attribute value

Employee DefaultAttributes Class

public class DefaultAttributes
{
    public string EmployeeName = "XYZ";
    public int[] ProjectCodes = new int[] { 1, 1 };
    public string city = "Munich";
}

XML File:

   <TopNode Id="A">
      <MiddleNode EmployeeName="John">
         <InnerMostNode Age="46" Average="88.15" ProjectCodes="46 112" City="Berlin">            
         </InnerMostNode>
      </MiddleNode>
      <MiddleNode EmployeeName="Claudia">
         <InnerMostNode Age="50" Average="96.58" ProjectCodes="9 510">            
         </InnerMostNode>
      </MiddleNode>
   </TopNode>

Use of Reflections To Override Default Values:

    private void OverrideAttribites(XmlNode xmlNode, DefaultAttributes nodeAttributes)
    {
        //Traverse through all fileds of DefaultAttributes class
        FieldInfo[] fieldsOfDefaultAttributesclass = typeof(DefaultAttributes).GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (var field in fieldsOfDefaultAttributesclass)
        {
            // Check if the "field" is present in the attributes of the current XML node
            string fieldName = field.Name;
            if (xmlNode.Attributes[fieldName] is not null) //i.e. field is present in the Attributes list
            {
                var attValue = xmlNode.Attributes[fieldName].Value;

                if (attValue.Contains(' ')) //i.e. attribute value should be stored in an array type
                {
                    if (!fieldName.Contains('['))
                    {
                        throw new Exception("Field type is not an array type but the XML attribute value contains an array");
                    }

                    //Set Array Value
                }
                else
                {
                    //PROBLEM: THIS LINE THROWS EXCEPTION !!!!!
                    field.SetValue(nodeAttributes, xmlNode.Attributes[fieldName].Value);
                }
            }
        }
    }

Question: The attributes values in my XML file are present string format. How do I use the attribute's value to set a field's value in a generic way (field could be int, double, int[] etc.)?





Aucun commentaire:

Enregistrer un commentaire