问题
Is it possible to implement a class constrained to two unique generic parameters?
If it is not, is that because it is unimplemented or because it would be impossible given the language structure (inheritance)?
I would like something of the form:
class BidirectionalMap<T1,T2> where T1 != T2
{
...
}
I am implementing a Bidirectional dictionary. This is mostly a question of curiosity, not of need.
Paraphrased from the comments:
Dan: "What are the negative consequence if this constraint is not met?"
Me: "Then the user could index with map[t1] and map[t2]. If they were the same type, there would be no distinction and it wouldn't make any sense."
Dan: The compiler actually allows [two generic type parameters to define distinct method overloads], so I'm curious; does it arbitrarily pick one of the methods to call?
回答1:
Expanding on the example to highlight the problem:
public class BidirectionalMap<T1,T2>
{
public void Remove(T1 item) {}
public void Remove(T2 item) {}
public static void Test()
{
//This line compiles
var possiblyBad = new BidirectionalMap<string, string>();
//This causes the compiler to fail with an ambiguous invocation
possiblyBad.Remove("Something");
}
}
So the answer is that, even though you can't specify the constraint T1 != T2, it doesn't matter, because the compiler will fail as soon as you try to do something that would violate the implicit constraint. It still catches the failure at compile time, so you can use these overloads with impunity. It's a bit odd, as you can create an instance of the map (and could even write IL code that manipulates the map appropriately), but the C# compiler won't let you wreak havoc by arbitrarily resolving ambiguous overloads.
One side note is that this kind of overloading could cause some odd behaviors if you're not careful. If you have a BidirectionalMap<Animal, Cat>
and Cat : Animal, consider what will happen with this code:
Animal animal = new Cat();
map.Remove(animal);
This will call the overload that takes Animal, so it will try to remove a key, even though you might have intended to remove the value Cat. This is a somewhat artificial case, but it's enough to warrant caution when very different behaviors occur as a result of method overloading. In such cases, it's probably easier to read and maintain if you just give the methods different names, reflecting their different behaviors (RemoveKey and RemoveValue, let's say.)
回答2:
The inequality wouldn't help the compiler to catch errors. When you specify constraints on type parameters, you are telling the compiler that variables of this type will always support a certain interface or will behave in certain ways. Each of those allows the compiler to validate something more like "this method will be present so it can be called on T".
The inequality of type parameters would be more like validating that method arguments are not null. It is part of the logic of the program, not its type safety.
回答3:
Type constraints seem like a misnomer. While they do contrain what the type parameter is, the purpose is to let the compiler know what operations are available to the type.
If you wanted to, you can have a constraint where T1 and T2 both derive from seperate concrete base classes, but I don't think that's quite what you want.
回答4:
I'm not entirely sure why this would be a desirable compile time check. It would be possible to essentially by-pass the condition by boxing either the key or the value, thereby rendering the compile-time check useless.
Some consideration needs to be made to determine... what errors am I trying to prevent?
If you are simply stopping a lazy co-worker from not reading the documentation, then add a Debug only check and throw an exception. This way the check can be removed for release code e.g.
#if Debug
if (T1 is T2 || T2 is T1)
{
throw new ArguementException(...);
}
#endif
If you are attempting to prevent a malevolent person from using your library in an unintended way, then perhaps a runtime check is needed, otherwise it would be easy to box the key or value.
回答5:
No, you cannot use equality (or inequality) as a constraint. Simply put, equality is not a constraint, but a condition. You should test for a condition such as equality or inequality of types in the constructor and throw an appropriate exception.
回答6:
There is no effective way to do this without imposing any other restrictions on the types themselves. As someone else noted, you could make constraints that the two types derived from two different base classes, but that's probably not very good from a design standpoint.
Edited to add: the reason this is not implemented is most likely because nobody at Microsoft ever considered something like this to be necessary to enforce at compile time, unlike the other constraints which have to do with how you're actually able to use variables of the specified types. And as some commenters have pointed out, you can certainly enforce this at runtime.
来源:https://stackoverflow.com/questions/8056588/a-generic-class-with-two-non-equal-unique-types