c#中myClass的双重性质

本文关键字:双重性 myClass | 更新日期: 2023-09-27 17:49:16

myclass在下面的例子中作为字符串以及myclass工作。

我知道每个人都会说这不是一个好习惯,使用下面的例子

代码:

class myClass
{
    public static void Main(string[] args)
    {   
        string @myClass = "my-Class";
        myClass.Replace("-", " ");  //myClass works as string
        myClass ob = new myClass();  //myClass works as myClass
        ob.i();
    }
    public void i()
    {
    }
}

但是我想知道:

  • 这是一个编译器错误吗?
  • 编译器如何管理这种双重性质?

c#中myClass的双重性质

你基本上只是做了一些看起来很奇怪的事情,但编译器可以根据上下文找出它。

string @myClass = "my-Class";

声明了一个名为myClass的字符串变量。在变量名上使用@允许你用通常不允许的名称创建变量(例如关键字)。在您的示例中,@是不需要的,因为myClass不是关键字,但您仍然可以使用它。在c#中,变量名前面的@符号是什么意思?

myClass.Replace("-", " ");

这是在myClass变量上调用string Replace方法。

myClass ob = new myClass();

这是在创建一个类型为"myClass"的新对象。编译器可以通过myClass的这种用法判断它指的是类型,而不是字符串变量。

注意,您甚至不需要@:

string myClass = "my-Class";

以上内容非常好。

你说:

compiler should give warning.

应该吗?实际上没有歧义。

考虑这个非常典型的场景:

public class MyRandom
{
    public Random Random { get; private set; }
    public MyRandom()
    {
        // Is this ambiguous? No--the left HAS to be the property;
        // the right HAS to be the type name.
        Random = new Random();
    }
}
变量的名称也是类型的名称的情况并不少见。只有当某些成员重叠时,才存在歧义。例如:
public class MyThreadPool
{
    public static void Add(Thread thread)
    {
        Console.WriteLine("Called the static method.");
    }
}
public class SomeOtherClass
{
    public List<Thread> MyThreadPool { get; private set; }
    public SomeOtherClass()
    {
        MyThreadPool = new List<Thread>();
    }
    public void DoSomethingAmbiguous()
    {
        // To me, it would make sense for the compiler to issue a warning here,
        // as it seems rather ambiguous (to me at least). However, it doesn't,
        // which tells me the behavior is defined somewhere in the spec (I'm too lazy
        // to check).
        MyThreadPool.Add(null);
    }
}

下面这行指的是你用string @myClass定义的字符串变量,而不是myClass类。

myClass.Replace("-", " ");  //myClass works as string

您使用myclass作为类型以及变量名称-编译器可以区分它们两者,只有当它们发生冲突时,您才会有问题-即在您的Main方法中,这将创建编译器错误:

myClass.Main(new string [1]);

第一个@myClass是一个实例名或变量名,这不会与类(类型)名myClass冲突。

所以没有错误或警告