传递null值超载方法,其中对象和String作为参数在C#对象、参数、方法、null

2023-09-04 02:39:01 作者:斬儘春風

我有这样两个重载方法如下

 公共类识别TestClass
    {

        公共无效LoadTest(对象参数)
        {
            Console.WriteLine(正在加载的对象......);
        }
        公共无效LoadTest(字符串参数)
        {
            Console.WriteLine(加载串......);
        }

    }
 

调用这个方法就像它下面会显示为加载字符串输出后... 请解释.NET处理这种情况?

 类节目
    {
        静态无效的主要(字串[] args)
        {
            VAR OBJ =新的识别TestClass();
            obj.LoadTest(空);
           // obj.LoadType(空);
            到Console.ReadLine();
        }
    }
 

解决方案

C#编译器采用最具体超载的可能。

由于字符串对象,它可以有空,编译器会认为字符串更具体。

SQL 关于空值 跟NULL 的区别

I have two overloaded methods like below

 public class TestClass
    {

        public void LoadTest(object param)
        {
            Console.WriteLine("Loading object...");
        }
        public void LoadTest(string param)
        {
            Console.WriteLine("Loading string...");
        }

    }

After calling this method like below it will show the output as Loading string... Please explain how .net handle this scenario?

 class Program
    {
        static void Main(string[] args)
        {       
            var obj=new TestClass();
            obj.LoadTest(null);
           // obj.LoadType(null);
            Console.ReadLine();
        }
    }

解决方案

The C# compiler takes the most specific overload possible.

As string is an object, and it can have the value of null, the compiler deems string to be more specific.