dynamic vs object type

前端 未结 4 1138
清酒与你
清酒与你 2020-12-01 14:10

I have used the dynamic and the object type interchangeably. Is there any difference between these two types? Is there any performance implications of using one over the oth

4条回答
  •  悲&欢浪女
    2020-12-01 14:29

    In simple language:
    Assume we have the following method:

    public static void ConsoleWrite(string inputArg)
    {
        Console.WriteLine(inputArg);
    }
    

    Object: the following code has compile error unless cast object to string:

    public static void Main(string[] args)
    {
        object obj = "String Sample";
        ConsoleWrite(obj);// compile error
        ConsoleWrite((string)obj); // correct
        Console.ReadKey();
    }
    

    dynamic: the following code compiles successfully but if it contains a value except string it throws Runtime error

    public static void Main(string[] args)
    {
        dynamic dyn = "String Sample";
        ConsoleWrite(dyn); // correct
        dyn = 1;
        ConsoleWrite(dyn);// Runtime Error
        Console.ReadKey();
    }
    

提交回复
热议问题