Property SetValue returns TargetParameterCountException

旧街凉风 提交于 2019-12-13 04:06:12

问题


TL;DR

I have the class Type for a XmlSerializer which throws a TargetParameterCountException on prop.SetValue().


Class Type

The class is called from my List Types

[System.Xml.Serialization.XmlArrayItemAttribute("Type", IsNullable = false)]
public List<Type> Types { get; set; }

and the class itself

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class Type
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public int TypeCode { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public int NumberOfUnits { get; set; }
    public bool ShouldSerializeNumberOfUnits() { return NumberOfUnits > 0; }
}

My Property Set Funktion

From: Xerillio answer for "Insert values in class without explicit writing them"

It's meant to automatically generate the full class with all subclasses filled with demo data.

public static void SetDefaults(object testObj)
{
    PropertyInfo[] propertyInfos = testObj.GetType().GetProperties();
    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        if (propertyInfo.Name == "Count" || propertyInfo.Name == "Capacity" || propertyInfo.SetMethod == null)
        {
            continue;
        }

        var propType = propertyInfo.PropertyType;
        if (propType == typeof(int))
        {
            // [...]
        }
        else
        {
            var ctor = propType.GetConstructor(Type.EmptyTypes);
            var propertyObject = ctor.Invoke(new object[0]);
            SetDefaults(propertyObject);
            propertyInfo.SetValue(testObj, propertyObject);
        }
    }
}

The Problem

Now if the propertyObject is written and ready to be set in propertyInfo it through the TargetParameterCountException.
May it has something to do with the unset index and count properties, but I can't find anything by STFW.

Do I need to set the count and index properties anywhere or does it have a problem with the ShouldSerialize... Variable?

来源:https://stackoverflow.com/questions/54708110/property-setvalue-returns-targetparametercountexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!