类型约束会影响方法声明消歧吗?

时间:2015-10-28 07:40:51

标签: c# generics type-constraints disambiguation

请考虑以下代码段:

protected object GetArg(Dictionary<string, object> args, string argName)
{
    object arg;
    if (args.TryGetValue(argName, out arg))
    {
        return arg;
    }
    return null;
}
protected T GetArg<T>(Dictionary<string, object> args, string argName) where T : class
{
    return GetArg(args, argName) as T;
}
//following does not compile: 
//Type ... already defines a member called 'GetArg' with the same parameter types
protected T GetArg<T>(Dictionary<string, object> args, string argName) where T : struct
{
    Nullable<T> arg = GetArg(args, argName) as Nullable<T>;
    return arg.HasValue ? arg.Value : default(T);
}

不应该将T参数类型限制在上述通用声明之间相互排斥,足以保证不明确吗?在这种情况下,为什么编译器不考虑类型约束?我有什么遗失的吗?

0 个答案:

没有答案