传入对象参数时如何区分 (object)null 和 (decimal?)null?

How to distinct between (object)null and (decimal?)null when passed in object parameter?

我已经创建了一个测试代码 snippet 来展示我正在努力实现的目标。但它没有按预期工作(请参阅代码中的注释):

public class Program
{
    public static void Main()
    {
        object obj = null;
        decimal? nullDecimal = null;

        Test(obj);         // Expected: Something else, Actual: Something else
        Test(nullDecimal); // Expected: Nullable decimal, Actual: Something else
    }

    public static void Test(object value)
    {
        if (value is decimal)
        {
            Console.WriteLine("Decimal");
            return;
        }

        if (value is decimal?)
        {
            Console.WriteLine("Nullable decimal");
            return;
        }

        Console.WriteLine("Something else");
    }
}

在 .NET 中甚至可能吗?

在您的示例中,无法确定它是 object 还是 decimal?。在这两种情况下,都只是传递了一个 null 引用,而没有传递类型信息。您可以使用泛型捕获类型信息:

public static void Main()
{
    object obj = null;
    decimal? nullDecimal = null;

    Test(obj);         // prints Something else
    Test(nullDecimal); // prints Nullable decimal
}

public static void Test<T>(T value)
{
    if (typeof(T) == typeof(decimal))
    {
        Console.WriteLine("Decimal");
        return;
    }

    if (typeof(T) == typeof(decimal?))
    {
        Console.WriteLine("Nullable decimal");
        return;
    }

    Console.WriteLine("Something else");
}

这样不管你传的值是不是null,编译时类型都会被自动捕获。