开发者

Can a type be a reference type and a value type at the same time?

If not and the set of reference types and value types are mutually exclusive, why doesn't this compile:

public static void Do<T>(T obj) where T : struct { }
public static void Do<T>(T obj) where T : class { }

The compiler states: "Type already defines a member called 'Do' with the same parameter types.", but T and T are not the same here. One is constrained to structs, the other is constraint to classes. A call to the function shoul开发者_如何学Pythond always be resolvable. Are there counter examples?


The generic constraints are not being taken as part of the overload match. It is the same as return type.

For example, this will lead to the same error (overloads differ only in return type):

public static int Do<T>(T obj) { }
public static bool Do<T>(T obj) { }

In both of these cases, the rules for matching an overload take into account only the parameters types, ignoring additional information such as constraints and return type.


No, types can never be both. The code fails because generic parameters (the <T>, that is, not the T obj) have no "overloading" concept. Nor is there anything resembling C++ template specialisation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜