如何获取对象的基础对象(而不仅仅是BaseType)

本文关键字:不仅仅是 BaseType 对象 何获 取对象 | 更新日期: 2023-09-27 18:20:28

我想知道如何获得对象的实际基对象?我有一个名为MessageBase的基类,以及许多继承该基类的类,这些类本身被不同深度的其他类继承。一个例子:

有些类继承如下:

MessageBase --> ValueMessage --> DoubleValueMessage

其他类似的:

MessageBase --> ValueMessage --> [some class] --> [some other class] --> TestMessage

我需要的是:我有一个继承类的对象,比方说DoubleValueMessage的实例。我事先不知道这个对象的类型,我只知道在嵌套继承的某个地方,有一个基对象(MessageBase)的属性我需要设置。

现在,我试图获得对该基础对象的引用。因此,我试图获得DoubleValueMessage所基于的ValueMessage,但我不明白是如何的。

我试过了:

public bool SetPropertyValue(object obj, string prop, object value)
{
    var item = obj.GetType().GetProperty(prop);
    //MessageBox.Show(obj.ToString());
    if (item != null)
    {
        item.SetValue(obj, value);
        return true;
    }
    else
    {
        if (obj.base != null)
        {
            SetPropertyValue(obj.base, prop, mb);
        }
    }
    return false;
}

其想法是:我传入一个对象(例如,类型为DoubleValueMessage)、我想要设置的属性(基本对象甚至是一个属性吗?)和一个需要替换给定属性的对象,在我的情况下是MessageBase。因此,我认为递归地向下迭代继承层次结构是一个好主意,直到找到我需要设置的属性。

问题是:.base关键字似乎不是获取基础对象的正确方法。

我怎样才能拿到它?提前感谢您的帮助!

如何获取对象的基础对象(而不仅仅是BaseType)

基对象不是一个单独的对象。派生对象是基础对象。您可以访问基属性,就好像它们是派生类的属性一样,除非这些属性是私有的。如果你想要基类的一个实例,那么投射对象,例如

var baseInstance = obj as MessageBase;

但听起来你其实并不需要这么做。

您可以使用以下代码获得基类型的私有属性:

public bool SetPropertyValue(object obj, string prop, object value) {
    var item = obj.GetType().BaseType.GetProperty(prop, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    //MessageBox.Show(obj.ToString());
    if (item != null) {
        item.SetValue(obj, value);
        return true;
    }
    return false;
}

请参阅http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx有关BindingFlags的详细信息。

对于多层继承,您可以执行以下操作:

public bool SetPropertyValue(object obj, string prop, object value) {
    var item = GetBaseType(obj.GetType()).GetProperty(prop, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    //MessageBox.Show(obj.ToString());
    if (item != null) {
        item.SetValue(obj, value);
        return true;
    }

    return false;
}
public Type GetBaseType(Type type) {
    if (type.BaseType != typeof(object)) {
        return GetBaseType(type.BaseType);
    }
    return type;
}
相关文章: