7

公共语言规范对方法重载非常严格。

方法只允许根据其参数的数量和类型进行重载,如果是泛型方法,则可以根据其泛型参数的数量进行重载。

为什么根据 csc,此代码符合 CLS(无 CS3006 警告)?

using System;

[assembly: CLSCompliant (true)]

public class Test {
    public static void Expect<T>(T arg)
    {
    }

    public static void Expect<T>(ref T arg)
    {
    }

    public static void Main ()
    {
    }
}
4

2 回答 2

2

这是符合 CLS 的,因为类型不同。重载规则要求满足一个(或多个)条件,而不是同时满足所有条件。

A ref T(或out T,使用相同类型的不同语义)正在声明对T引用(对于类)或实例(在值类型的情况下)的“引用”。

有关更多详细信息,请查看该Type.MakeByRefType()方法 - 它创建表示对原始类型的引用的类型,例如对于 aT这返回 a T&(在 C++ 表示法中)。

于 2012-09-26T09:17:32.297 回答
0

To be clear, in general, overloaded methods differing only in ref or out, or in array rank, are not CLS-compliant, according to MSDN.

You can verify the compiler does indeed check for this specific case by writing a simple non-generic version:

using System;

[assembly: CLSCompliant (true)]

public class Test {
    public static void Expect(int arg)
    {
    }

    public static void Expect(ref int arg)
    {
    }

    public static void Main ()
    {
    }
}

However, you seem to have hit upon a compiler edge-case, since if you add in the generic method overloads, the compiler doesn't seem to complain.

I would say this is either a bug in the compiler (as in this similar question), or there is indeed a more relaxed specification for generics, since they are a latter addition to the specification.

I would err on the side of some kind of compiler limitation, given that this example also raises CS3006:

using System;

[assembly: CLSCompliant(true)]

public class Test<T>
{
    public static void Expect(T arg)
    {
    }

    public static void Expect(ref T arg)
    {
    }

    public static void Main()
    {
    }
}

Apparently adding the generics to the class, rather than the method, raises the compiler's attention...

于 2014-08-12T08:20:36.460 回答