在具有某些相同属性的层次结构中处理不同 类 的最有效方法是什么

What's the most efficient way to handle different classes in a hierarchy with some same properties

我已经搜索过是否已经存在关于此的问题,如果我错过了,我深表歉意。

我有一个复杂的 class 结构,我从 运行 xsd.exe 在 xml 架构上生成的绑定嵌入到我的代码中,所以我没有创建结构,但我不得不处理它。

层次结构中的 classes 中有一些属性是重复的。出于保密原因,我不能 post 实际代码,但是例如,如果我有一个基础 class,其中有 10 个 class 继承自它,其中 8 个有一个 属性在它们中称为 WidgetValue,我怎样才能最有效地处理这个问题?

目前我在想我将不得不检查每个继承 classes 的类型,然后转换为它们中的每一个以访问 WidgetValue 属性.

有没有更好的方法可以解决这个问题?

正如已经指出的那样,您不应修改生成的 类,因为如果出于任何原因您需要重新生成它们,您还需要重新修改它们。

所以,我会:

  • 使用dynamic,或
  • 使用Reflection

但首先,这是我用于测试的模型:

public class MainClass
{
    public string MainProp { get; set; }
}

public class ClassA : MainClass
{
    public string SomeProp { get; set; }

    public string WidgetValue { get; set; }
}

public class ClassB : MainClass
{
    public string SomeOtherProp { get; set; }

    public string WidgetValue { get; set; }
}

public class ClassC : MainClass
{
    public string AnotherProp { get; set; }

    public string WidgetValue { get; set; }
}

public class ClassD : MainClass
{
    public string Different { get; set; }
}

这就是使用 dynamicReflection:

获取 WidgetValue 的方法
static void GetWidgetValue(MainClass obj)
    {
        Type[] typesThatHaveWidgetValue = new Type[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) };

        if (typesThatHaveWidgetValue.Contains(obj.GetType()))
        {
            dynamic o = obj;
            Console.WriteLine(o.WidgetValue);
        }
        else
        {
            Console.WriteLine("Object don't have property 'WidgetValue'");
        }
    }

    static void GetWidgetValueWithReflection(MainClass obj)
    {
        var type = obj.GetType();
        var widgetValueProp = type.GetProperty("WidgetValue");
        if (widgetValueProp != null)
        {
            var widgetValue = widgetValueProp.GetValue(obj);
            Console.WriteLine(widgetValue);
        }
        else
        {
            Console.WriteLine("Object don't have property 'WidgetValue'");
        }
    }

这就是您测试它的方式:

var classA = new ClassA { WidgetValue = "The Value" };
        var classB = new ClassB { WidgetValue = "The Other Value" };
        var classD = new ClassD();

        GetWidgetValue(classA); // The Value
        GetWidgetValue(classB); // The Other Value
        GetWidgetValue(classD); // Object don't have property 'WidgetValue'

        GetWidgetValueWithReflection(classA); // The Value
        GetWidgetValueWithReflection(classB); // The Other Value
        GetWidgetValueWithReflection(classD); // Object don't have property 'WidgetValue'

然后你避免做这样的事情:

if (obj.GetType() == typeof(ClassA))
{
    var classA = (ClassA)obj;
    Console.WriteLine(classA.WidgetValue);
}
else if (obj.GetType() == typeof(ClassB))
{
    var classB = (ClassB)obj;
    Console.WriteLine(classB.WidgetValue);
} ...