【问题标题】:What's an elegant solution to get the property values from two classes (that have the same property names) that do not use inheritance?从不使用继承的两个类(具有相同的属性名称)中获取属性值的优雅解决方案是什么?
【发布时间】:2011-02-16 18:01:26
【问题描述】:

基本上,我必须使用由其他程序员维护的实施不佳的 Web 服务。它们有两个不是从父类派生的类,但具有相同的属性(呃……)。所以它在我的网络服务代理类文件中看起来像这样:

public partial class Product1
{
    public int Quantity;
    public int Price;
}

public partial class Product2
{
    public int Quantity;
    public int Price;
}

那么在不复制代码的情况下从已知属性中获取值的最佳方法是什么?我知道我可能可以使用反射,但这会变得很难看。如果有更简单、不那么疯狂的方法(也许在新的 c# 功能中?)请告诉我。

【问题讨论】:

  • 你能完全改变课程吗?
  • 你能在Product类中添加代码吗?
  • 我可能可以,因为我正在做的是从 web 服务创建一个代理类并使用它,但是如果他们更新 web 服务并且我重新创建代理类我会很难维护必须记住我所做的改变并每次都做出改变。

标签: c# web-services reflection class properties


【解决方案1】:

4.0 中的动态关键字?但我不会说它很优雅,但它会起作用。

【讨论】:

  • 虽然它可能会起作用,但它不应该被用作糟糕设计的拐杖,但如果这是唯一剩下的解决方案,那么我会说它比反射更好。
  • 是的,我完全同意你的观点,这就是为什么我说它不优雅。
  • 我的全部工作都是处理糟糕的设计。这真的很令人沮丧,所以我不确定我还能做什么。我可能可以告诉人们改变它,但那是另一回事。我很确定这将是我唯一一次必须使用它。
【解决方案2】:

这里有一些伪代码,抱歉没有解决。也许这会给你正确的方向:

列表对象 = new List(); objects.Add(p1);//你的第一个产品对象 objects.Add(p2);//你的第二个产品对象

    foreach (var o in objects)//go through all projects
    {

        if (o.GetType().Equals(typeof(Product1)) //check which class is behind the object
            ((Product1)o).Price = 2; //convert to fitting class and call your property
        //....
    }

【讨论】:

    【解决方案3】:

    我不确定我是否完全了解您的情况,但也许是这样的? 用getQuantity和getPrice方法定义一个IProduct接口,并在两个类中实现:

    public partial class Product1 : IProduct
    {
      public int Quantity;
      public int Price;
      public int getQuantity() { return Quantity; }
      public int getPrice() { return Price; }
    }
    

    另一个类似;然后将它们都用作IProduct。

    【讨论】:

    • 对不起,我意识到我没有说清楚并相应地改变了问题。这是我无法控制但必须使用的 Web 服务。否则我会像一个优秀的程序员那样使用继承,或者更好的是没有两个具有相同属性的单独类。
    • 没关系,我明白你在说什么。它是一个部分类的事实有所帮助,因为我可以在我自己的代码中修改该类而无需编辑代理文件,完全掩盖了这一点。谢谢。
    【解决方案4】:

    如果类是从 Web 代理生成的,那么您可以实现一个部分类来实现一个通用接口。

    来自代理生成:

    public partial class Product1 {
        public int Quantity;
        public int Price;
    }
    
    public partial class Product2 {
        public int Quantity;
        public int Price;
    }
    

    手写:

    public interface IProduct {
        int Quantity { get; }
        int Price { get; }
    }
    
    public partial class Product1:IProduct {
        int IProduct.Quantity { get { return Quantity; } }
        int IProduct.Price { get { return Price; } }
    }
    
    public partial class Product2:IProduct {
        int IProduct.Quantity { get { return Quantity; } }
        int IProduct.Price { get { return Price; } }
    }
    

    现在您的两个类都实现了IProduct,并且可以以相同的方式传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 2022-01-20
      • 2018-01-01
      相关资源
      最近更新 更多