【问题标题】:C# code re-use public class Foo<T> method parametersC# 代码重用公共类 Foo<T> 方法参数
【发布时间】:2013-04-21 07:21:19
【问题描述】:

我希望有人可以帮助我解决问题。我正在尝试创建一个新的类型类:

public class Foo<T>

其唯一方法的工作是遍历另一个类的属性。大约有 20 个类,定义了不同数量的属性:

public class Bar {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Shirt {
    public string Color { get; set; }
    public string Size { get; set; }
    public string Brand { get; set; }
}

public class Pants {
    public string Color { get; set; }
    public string Waist { get; set; }
    public string Length { get; set; }
    public string Inseam { get; set; }
}

而公共类Foo的方法是:

public class Foo<T> {
    public string FooMethod(T before, T after /* other variables? */) {
        // compare before & after
    }
}

每个名称相同的类将进入Foo 的主方法两次,但属性值不同。所以Bar 之前的 ID 和名称 可以是 1 &amp; "Bar"Bar 之后的 ID 和名称 可以是 2 &amp; "BarBar"

从这里开始,将进行其他操作来比较之前和之后中的每个属性。但是,由于每个类中的属性数量各不相同,而且我只想使用一种方法,因此我进退两难。

【问题讨论】:

  • 你经常使用“构造函数”这个词,但你没有构造函数。您的意思是使用“属性”而不是“构造函数”吗?
  • 是的,我的措辞不正确,感谢您的澄清和回复。

标签: c# types constructor code-reuse


【解决方案1】:

如果你想在你的 FooMethod 中比较多种类型的对象,你可以在你的所有类(Bar、Shirt、Pants ...)中重写 Equals 和 GetHashcode 方法,并在那里进行比较。这样你的 FooMethod 只会调用before.Equals(after) 来比较它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多