简体   繁体   中英

C# code re-use public class Foo<T> method parameters

I was hoping someone could help me with a problem. I am attempting to make a new class of Type:

public class Foo<T>

whose only method's job is to iterate through another classes' properties. There are about 20 classes with a varying amount of properties defined:

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; }
}

And public class Foo's method is:

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

Each class that is named the same is going to go into Foo 's primary method twice, but with different property values. So Bar before's Id & Name could be 1 & "Bar" while Bar after's Id & Name could be 2 & "BarBar" .

From here, other operations are going to be done to compare each property in before & after . However, since the number of properties in each class varies, and I am only looking to use one method I have a dilemma.

If you want in your FooMethod to compare object of multiple types, you can override Equals and GetHashcode methods in all your classes(Bar, Shirt, Pants ...), and do comparison there. That way your FooMethod will only call before.Equals(after) to compare them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM