C# 代码重用公共类 Foo<T> 方法参数



我希望有人能帮我解决一个问题。我正在尝试创建一个类型为:

的新类
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 & "Bar", Bar 在Id &amp后;名称可以是2 & "BarBar"

从这里开始,将执行其他操作来比较&之前中的每个属性。然而,由于每个类中的属性数量各不相同,而我只想使用一种方法,因此我陷入了两难境地。

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

最新更新