【问题标题】:Treat subclass as its superclass when only a member differs by its type当只有一个成员的类型不同时,将子类视为其超类
【发布时间】:2009-02-12 10:50:26
【问题描述】:

我有一个变量类和 3 个子类:VariableBool、VariableLong 和 VariableDouble。每个子类只定义一个后缀类型的值成员。

现在,我需要通过 WCF 传输基于这些类的对象。我有多个客户将他们的变量注册到服务器。每当一个客户端上的值发生变化时,它都会在所有其他客户端中更新。

我的问题是:有没有办法:

someVar.Value = anotherVar.Value;

无论类型如何,都无需检查类型,例如:

VariableBool anotherVarBool = anotherVar as VariableBool;
if (anotherVarBool != null) {
  (someVar as VariableBool).Value = anotherVar.Value;
}
// check other types...

我错过了什么?有没有某种模式?我可以使用反射吗? 另外,由于 WCF,我认为我不能使用泛型(我已经尝试过,但我可以让它工作)。

谢谢

【问题讨论】:

    标签: c# .net wcf


    【解决方案1】:

    如果您使用的是 mex 生成的 WCF 代理,那么我怀疑反射(或 ComponentModel)确实是最简单的选项 - 类似于:

    public static void Copy<T>(T source, T destination,
        string propertyName) {
        PropertyInfo prop = typeof(T).GetProperty(propertyName);
        prop.SetValue(destination, prop.GetValue(source, null), null);
    }
    

    或者如果你想使用它,即使变量类型作为基类:

    public static void Copy(object source, object destination,
        string propertyName) {
        PropertyInfo sourceProp = source.GetType().GetProperty(propertyName);
        PropertyInfo destProp = destination.GetType().GetProperty(propertyName);
        destProp.SetValue(destination, sourceProp.GetValue(source, null), null);
    }
    

    【讨论】:

    • 谢谢,这正是我想要的:)
    【解决方案2】:

    为什么不把 Value 成员放在基类变量中。 在这种情况下,

    public void UpdateValue( Variable variable )
    {
       if( variable != null )
          // do something with variable.Value
    }
    

    但是,如果你真的想使用继承,你需要通过 KnownType 属性及其方法告诉基类有哪些子类型

    [DataContract()]
    [KnownType( "GetKnownType" )]
    public class Variable
    {
    
     public object Value;
    
     private static Type[] GetKnownType()
     {
       // properties
       return new []{ typeof(VariableBool),
                      typeof(VariableLong), 
                      typeof(VariableDouble),};
     }
    }
    
    [DataContract()]
    public class VariableBool : Variable
    {
    }
    
    [DataContract()]
    public class VariableLong : Variable
    {
    }
    
    [DataContract()]
    public class VariableDouble : Variable
    {
    }
    

    【讨论】:

    • 谢谢,我会将您的回答与解决方案结合起来。子类将仅用于获取类型化值
    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多