继承类方法的延迟类型推断

时间:2015-06-10 14:41:50

标签: c# inheritance

我尝试做的事情没有成功,是基类的一种方法,它使用反射来更新定义为继承类的属性。所以,从这样的特定方法开始

/** fill the item from a xml node
 */
public TblItem FromXML (XmlNode itemNode)
{
    foreach (XmlNode itemField in itemNode) {
        Type myType = this.GetType ();
        PropertyInfo myPropInfo = myType.GetProperty (itemField.Name);
        if (myPropInfo != null) {
            myPropInfo.SetValue (this, Convert.ChangeType (itemField.InnerText, myPropInfo.PropertyType), null);
        } else {            
            throw new MissingFieldException (string.Format ("[Fieldname]wrong fieldname: {0}", itemField.Name));
        }
    }
    return this;
}

我需要在名为 TblBase 的基类中定义它,根本不包含任何属性,并在所有派生类中无缝使用,即 TblDerived1:TblBase 等等,为每个人定义了不同的属性,所以我在这里问:有没有办法做到这一点,或者这只是我肮脏心灵的梦想? 顺便说一句,这就是我需要使用这些东西的方式:

    xmlDoc.Load (XMLDbPath); 
    XmlNodeList itemNodes = xmlDoc.SelectNodes (nodes2select);
    //Tblitem inherits TblBase
    TblItem ti = new TblItem ();
    foreach (XmlNode itemNode in itemNodes) {
        print (((TblItem)ti).FromXML (itemNode).ToString ());
    }

1 个答案:

答案 0 :(得分:1)

使用下面的泛型查看代码,我用名称和值替换了xml节点,以便我可以测试。

  public T FromXML<T>(string name, string value) where T: TblBase
            {
                Type myType = this.GetType();
                PropertyInfo myPropInfo = myType.GetProperty(name);
                if (myPropInfo != null)
                {
                    myPropInfo.SetValue(this, Convert.ChangeType(value, myPropInfo.PropertyType), null);
                }
                else
                {
                    throw new MissingFieldException(string.Format("[Fieldname]wrong fieldname: {0}", name));
                }
                return (T)this;
            }

并称之为: var result = yourItem.FromXML(someName,someValue);

但是,它也可以在没有泛型的情况下工作:

    public TblBase FromXML (XmlNode itemNode)
{
    foreach (XmlNode itemField in itemNode) {
        Type myType = this.GetType ();
        PropertyInfo myPropInfo = myType.GetProperty (itemField.Name);
        if (myPropInfo != null) {
            myPropInfo.SetValue (this, Convert.ChangeType (itemField.InnerText, myPropInfo.PropertyType), null);
        } else {            
            throw new MissingFieldException (string.Format ("[Fieldname]wrong fieldname: {0}", itemField.Name));
        }
    }
    return this;
}

并称之为: TblItem result =(TblItem)yourItem.FromXml(...);

编辑:

这适用于属性(使用get和set)。如果您想要以相同方式更改字段数据成员,则需要使用GetField而不是GetProperty:

var myFieldInfo = myType.GetField(name)
...
myFieldInfo.SetValue (this, Convert.ChangeType (itemField.InnerText, myFieldInfo.FieldType));