简体   繁体   中英

C# Generics and Type Safety at Runtime

I'm not even really sure how best to phrase the question, but I'll see what I can do.

I have a goal, but I'm not sure how to, or if I even can, achieve it.

Let's say I have a type Sport . And then there's a Team<Sport> and a Player<Sport> . I'd like to make it such that any time I have a Team and a Player interact via methods, they can only do so if they have the same <Sport> type.

For instance: Team<Sport>.AddPlayer( Player<Sport> player) <- How can I make it so this can only be called when both Sport s are the same type? If I have to derive new types from Sport , that could work, but I was hoping to do it based on instance at runtime.

I know the compiler won't know about the instances ahead of time, so I guess I'm wondering if there's some kind of type safety magic you can do to make it so I don't have to compare the types myself every time.

You can't put instances into <> in C#. To achieve "type safety" you need to have actual "types" called Tennis , Hockey , Badminton etc. Otherwise the compiler cannot distinguish between sports.

Either you check whether the types of sports are the same at runtime, or you create subclasses of Sport , like Tennis , Badminton and Hockey . Since you want type safety at compile time, you should use the latter approach.

You can do something like:

var tennisTeam = new Team<Tennis>();
tennisTeam.AddPlayer(new Player<Tennis>());

Team can be defined like this:

class Team<TSport> where TSport : Sport {
    public void AddPlayer(Player<TSport> player) {
        // ...
    }
    // ...
}

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