简体   繁体   中英

Specify type *and* interface(s) of function parameter

I have a structure of classes that I'd like to apply some odd constraints to:

public abstract class TopClass {}

public class ClassA : Topclass {}
public class ClassB : Topclass {}
public class ClassC : Topclass {}
public class ClassD : Topclass {}
public class ClassE : Topclass {}

I'd like to group these into categories, some of which overlap, so I can require this combination or that when using TopClass . Since C# doesn't support multiple inheritances, I've been trying to use interfaces:

public abstract class TopClass {}

public interface IGroupA {}
public interface IGroupB {}

public class ClassA : Topclass, IGroupA          {}
public class ClassB : Topclass, IGroupA          {}
public class ClassC : Topclass, IGroupA, IGroupB {}
public class ClassD : Topclass, IGroupB          {}
public class ClassE : Topclass, IGroupB          {}

This all works fine, but actually using this craziness is where I run into trouble. I can't figure out how to specify that a parameter for a function should be of type TopClass and implement interface IGroupA . IE, I would like to be able to target classes ClassA , ClassB , and ClassC without explicitly naming them (so that a developer in charge of TopClass and it's decedents could easily redefine the groups without interfering with other developers).

You could use generic constraints and you can specify both a class that the type should derive from and interface(s) that type should implement:

void MyFunction<T>(T argument) where T : TopClass, IGroupA
{

}

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